private JSONObject buildAuthorizationResponse(Session session) throws JSONException {
    JSONObject response = new JSONObject();

    if (session.getState().isOpened()) {
      response.put("status", "connected");
    } else if (session.getState() == SessionState.CLOSED_LOGIN_FAILED) {
      response.put("status", "not_authorized");
    } else {
      response.put("status", "unknown");
    }

    return response;
  }
 public void onResume() {
   // For scenarios where the main activity is launched and user
   // session is not null, the session state change notification
   // may not be triggered. Trigger it if it's open/closed.
   Session session = Session.getActiveSession();
   if (session != null && (session.isOpened() || session.isClosed())) {
     if (session.getState().isOpened()) {
       Log.i(TAG, "Logged in...");
     } else if (session.getState().isClosed()) {
       Log.i(TAG, "Logged out...");
     }
   }
   uiHelper.onResume();
 }
示例#3
0
 private void openSession(
     String applicationId,
     List<String> permissions,
     SessionLoginBehavior behavior,
     int activityCode,
     SessionAuthorizationType authType) {
   if (sessionTracker != null) {
     Session currentSession = sessionTracker.getSession();
     if (currentSession == null || currentSession.getState().isClosed()) {
       Session session =
           new Session.Builder(getActivity()).setApplicationId(applicationId).build();
       Session.setActiveSession(session);
       currentSession = session;
     }
     if (!currentSession.isOpened()) {
       Session.OpenRequest openRequest =
           new Session.OpenRequest(this)
               .setPermissions(permissions)
               .setLoginBehavior(behavior)
               .setRequestCode(activityCode);
       if (SessionAuthorizationType.PUBLISH.equals(authType)) {
         currentSession.openForPublish(openRequest);
       } else {
         currentSession.openForRead(openRequest);
       }
     }
   }
 }
示例#4
0
 /**
  * Gets the current state of the session or null if no session has been created.
  *
  * @return the current state of the session
  */
 protected final SessionState getSessionState() {
   if (sessionTracker != null) {
     Session currentSession = sessionTracker.getSession();
     return (currentSession != null) ? currentSession.getState() : null;
   }
   return null;
 }
 public static void getLoginStatus(int cbIndex, boolean force) {
   Log.v(TAG, "getLoginStatus" + cbIndex);
   Session session = Session.getActiveSession();
   if (session == null) {
     nativeCallback(cbIndex, "{\"authResponse\":null,\"status\":\"unknown\"}");
   } else {
     if (session.isOpened()) {
       nativeCallback(
           cbIndex,
           "{\"authResponse\":{\"accessToken\":\""
               + session.getAccessToken()
               + "\"},\"status\":\"connected\"}");
     } else if (session.getState() == SessionState.CLOSED_LOGIN_FAILED) {
       nativeCallback(
           cbIndex,
           "{\"authResponse\":{\"accessToken\":\""
               + session.getAccessToken()
               + "\"},\"status\":\"not_authorized\"}");
     } else {
       nativeCallback(
           cbIndex,
           "{\"authResponse\":{\"accessToken\":\""
               + session.getAccessToken()
               + "\"},\"status\":\"unknown\"}");
     }
   }
 }
  public static void init(String appID) {
    Session session;
    if (FB.isLoggedIn()) {
      session = Session.getActiveSession();
      // this shouldn't be an issue for most people: the app id in the session not matching the one
      // provided
      // instead it can probably happen if a developer wants to switch app ids at run time.
      if (appID != session.getApplicationId()) {
        Log.w(
            FB.TAG,
            "App Id in active session ("
                + session.getApplicationId()
                + ") doesn't match App Id passed in: "
                + appID);
        session = new Builder(FB.getUnityActivity()).setApplicationId(appID).build();
      }
    } else {
      session = new Builder(FB.getUnityActivity()).setApplicationId(appID).build();
    }
    Session.setActiveSession(session);

    final UnityMessage unityMessage = new UnityMessage("OnInitComplete");
    unityMessage.put("key_hash", FB.getKeyHash());

    // if there is an existing session, reopen it
    if (SessionState.CREATED_TOKEN_LOADED.equals(session.getState())) {
      Session.StatusCallback finalCallback = getFinalCallback(unityMessage, null);
      sessionOpenRequest(session, finalCallback, FB.getUnityActivity(), null, false);
    } else {
      unityMessage.send();
    }
  }
  private Session getSession() {
    Session session = Session.getActiveSession();

    if (session == null || session.getState().isClosed()) {
      Log.d(TAG, "building session");
      session = new Session.Builder(cordova.getActivity()).setApplicationId(this.appId).build();

      if (session.getState() == SessionState.CREATED_TOKEN_LOADED) {
        Log.d(TAG, "opening session");
        session.openForRead(null);
      }

      Session.setActiveSession(session);
    }

    return session;
  }
 private Session createSession() {
   Session activeSession = Session.getActiveSession();
   if (activeSession == null || activeSession.getState().isClosed()) {
     activeSession = new Session.Builder(this).setApplicationId(appId).build();
     Session.setActiveSession(activeSession);
   }
   return activeSession;
 }
  private void login(JSONArray args, CallbackContext callbackContext) throws JSONException {
    Session session = Session.getActiveSession();

    if (session == null || session.isClosed()) {
      Log.d(TAG, "Building new session");
      session = new Session.Builder(cordova.getActivity()).setApplicationId(this.appId).build();
      Session.setActiveSession(session);
    } else {
      Log.d(TAG, "Existing session " + session.getState());
    }

    if (session.isOpened()) {
      Log.d(TAG, "Session already open");
      callbackContext.success(buildAuthorizationResponse(session));
      return;
    }

    final CallbackContext callback = callbackContext;

    List<String> permissions = new ArrayList<String>();

    permissions.add("basic_info");
    JSONArray argumentPermissions = args.getJSONArray(0);

    for (int i = 0; i < argumentPermissions.length(); i++) {
      permissions.add(argumentPermissions.getString(i));
    }

    OpenRequest openRequest =
        new OpenRequest(cordova.getActivity())
            .setPermissions(permissions)
            .setCallback(
                new StatusCallback() {
                  @Override
                  public void call(Session session, SessionState state, Exception exception) {
                    Log.d(TAG, "In status callback open for read " + state);

                    if (state == SessionState.OPENING) {
                      return;
                    }

                    session.removeCallback(this);

                    try {
                      JSONObject response = buildAuthorizationResponse(session);

                      callback.success(response);
                    } catch (JSONException e) {
                      Log.e(TAG, "JSONException", e);
                      callback.error(e.toString());
                    }
                  }
                });

    cordova.setActivityResultCallback(this);

    session.openForRead(openRequest);
  }
示例#10
0
 @Override
 protected void onResume() {
   super.onResume();
   // For scenarios where the main activity is launched and user
   // session is not null, the session state change notification
   // may not be triggered. Trigger it if it's open/closed.
   Session session = Session.getActiveSession();
   if (session != null && (session.isOpened() || session.isClosed())) {
     onSessionStateChange(session, session.getState(), null);
   }
   uiHelper.onResume();
 }
示例#11
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.alubumlistview);
    alubumlistview = (ListView) findViewById(R.id.alubumlistview);
    imagegallerytextview = (TextView) findViewById(R.id.imagegallerytextview);
    Ultilities mUltilities = new Ultilities();
    int imageHeightAndWidht[] = mUltilities.getImageHeightAndWidthForAlubumListview(this);
    alubumList = new ArrayList<ListviewAlubumData>();
    mAlubumListViewAdapter = new AlubumListViewAdapter(this, alubumList, imageHeightAndWidht);
    alubumlistview.setAdapter(mAlubumListViewAdapter);
    imagegallerytextview.setText("Albums");
    Typeface HelveticaLTStd_Light =
        Typeface.createFromAsset(getAssets(), "fonts/HelveticaLTStd-Light.otf");
    imagegallerytextview.setTypeface(HelveticaLTStd_Light);
    imagegallerytextview.setTextColor(Color.rgb(255, 255, 255));
    imagegallerytextview.setTextSize(20);
    Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
    Session session = Session.getActiveSession();

    logDebug("onCreate session " + session);
    if (session == null) { // logDebug("onCreate savedInstanceState "+savedInstanceState);
      if (savedInstanceState != null) {
        session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
        // logDebug("onCreate savedInstanceState restore session   "+session);
      }
      if (session == null) {
        session = new Session(this);
        // logDebug("onCreate savedInstanceState create session   "+session);
      }
      Session.setActiveSession(session);
      // logDebug("onCreate savedInstanceState state session    "+session.getState());
      if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
        // session.openForRead(new
        // Session.OpenRequest(this).setPermissions(Arrays.asList("user_birthday",
        // "email","user_relationships","user_photos")).setCallback(statusCallback));
      }
    }

    try {
      if (session.isOpened()) {
        getUserAllAlubum();
      } else {
        getOpenedSession();
      }
      alubumlistview.setOnItemClickListener(this);
      ;

    } catch (Exception e) {
      logError("error onCreate Exception " + e);
    }
  }
  private void getPermissions(CallbackContext callbackContext) throws JSONException {
    Session session = getSession();

    if (!session.getState().isOpened()) {
      callbackContext.success("login_required");
      return;
    }
    Log.d(TAG, "Permissions: " + Arrays.toString(session.getPermissions().toArray()));
    JSONObject response = new JSONObject();

    for (String permission : session.getPermissions()) {
      response.put(permission, 1);
    }

    callbackContext.success(response);
  }
示例#13
0
  private void initFacebook(Bundle savedInstanceState) {
    Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

    Session session = Session.getActiveSession();
    if (session != null) {
      return;
    }
    if (savedInstanceState != null) {
      session = Session.restoreSession(activity, null, facebookStatusCallback, savedInstanceState);
    }
    if (session == null) {
      session = new Session(activity);
    }
    Session.setActiveSession(session);
    if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
      session.openForRead(new Session.OpenRequest(activity).setCallback(facebookStatusCallback));
    }
  }
示例#14
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Add code to print out the key hash
    /* try {
        PackageInfo info = getPackageManager().getPackageInfo(
                "com.coupers.coupers",
                PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    } catch (PackageManager.NameNotFoundException e) {

    } catch (NoSuchAlgorithmException e) {

    }*/
    setTitle(R.string.main_hub_ui);

    // TODO Get all preferences data up front
    login_method =
        PreferenceManager.getDefaultSharedPreferences(this)
            .getInt("login_method", NO_METHOD_DEFINED);
    user_id =
        PreferenceManager.getDefaultSharedPreferences(this)
            .getString("user_id", NO_USER_ID_AVAILABLE);
    registered =
        PreferenceManager.getDefaultSharedPreferences(this).getBoolean("registered", false);
    first_time = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("first_time", true);
    String closest_city = GetClosestCityName();
    user_location = closest_city.toLowerCase();
    if (user_location.equals(getString(R.string.no_locality_found))) {
      user_location =
          PreferenceManager.getDefaultSharedPreferences(this)
              .getString("user_location", NO_LOCATION_AVAILABLE);
    } else {
      PreferenceManager.getDefaultSharedPreferences(this)
          .edit()
          .putString("user_location", user_location)
          .commit();
    }
    if (!user_location.equals(NO_LOCATION_AVAILABLE) && !first_time) city_selected = true;

    // Initialize
    // Coupers App
    app = (CoupersApp) getApplication();
    app.initialize(this);
    app.setUser_id(user_id);

    // Facebook Helper
    uiHelper = new UiLifecycleHelper(this, callback);
    uiHelper.onCreate(savedInstanceState);

    // Register GCM Service
    if (checkPlayServices()) {
      gcm = GoogleCloudMessaging.getInstance(this);
      regid = getRegistrationId(this);

      if (regid.isEmpty()) registerInBackground();
      else {
        // sendRegistrationIdToBackend(regid);
        Log.i(TAG, regid);
      }
    } else Log.i(TAG, "No valid Google Play Services APK found.");

    a = this;

    // First time loading or no data found
    if (login_method == NO_METHOD_DEFINED) {
      // Login screen
      setContentView(R.layout.activity_login_only_facebook);
    } else if (login_method == FACEBOOK_LOGIN) {
      // Facebook UI Helper to keep track of session state

      Session session = Session.getActiveSession();
      if (session != null && session.isOpened()) {
        setContentView(R.layout.activity_start);
        initiateLoading();
      } else if (session != null && session.getState() == SessionState.CREATED_TOKEN_LOADED) {
        setContentView(R.layout.activity_start);
      } else setContentView(R.layout.activity_login_only_facebook);
    } else {
      setContentView(R.layout.activity_login_only_facebook);
    }
  }
    @Override
    public void onClick(View v) {
      Context context = getContext();
      final Session openSession = sessionTracker.getOpenSession();
      if (openSession != null) {
        // If the Session is currently open, it must mean we need to log out
        if (confirmLogout) {
          // Create a confirmation dialog
          String logout = getResources().getString(R.string.com_facebook_loginview_log_out_action);
          String cancel = getResources().getString(R.string.com_facebook_loginview_cancel_action);
          String message;
          if (user != null && user.getName() != null) {
            message =
                String.format(
                    getResources().getString(R.string.com_facebook_loginview_logged_in_as),
                    user.getName());
          } else {
            message =
                getResources().getString(R.string.com_facebook_loginview_logged_in_using_facebook);
          }
          AlertDialog.Builder builder = new AlertDialog.Builder(context);
          builder
              .setMessage(message)
              .setCancelable(true)
              .setPositiveButton(
                  logout,
                  new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                      openSession.closeAndClearTokenInformation();
                    }
                  })
              .setNegativeButton(cancel, null);
          builder.create().show();
        } else {
          openSession.closeAndClearTokenInformation();
        }
      } else {
        Session currentSession = sessionTracker.getSession();
        if (currentSession == null || currentSession.getState().isClosed()) {
          sessionTracker.setSession(null);
          Session session = new Session.Builder(context).setApplicationId(applicationId).build();
          Session.setActiveSession(session);
          currentSession = session;
        }
        if (!currentSession.isOpened()) {
          Session.OpenRequest openRequest = null;
          if (parentFragment != null) {
            openRequest = new Session.OpenRequest(parentFragment);
          } else if (context instanceof Activity) {
            openRequest = new Session.OpenRequest((Activity) context);
          }

          if (openRequest != null) {
            openRequest.setDefaultAudience(properties.defaultAudience);
            openRequest.setPermissions(properties.permissions);
            openRequest.setLoginBehavior(properties.loginBehavior);

            if (SessionAuthorizationType.PUBLISH.equals(properties.authorizationType)) {
              currentSession.openForPublish(openRequest);
            } else {
              currentSession.openForRead(openRequest);
            }
          }
        }
      }
    }
示例#16
0
 // call this in onResume of activity
 public void onResume() {
   Session session = Session.getActiveSession();
   if (session != null && (session.isOpened() || session.isClosed())) {
     onSessionStateChange(session, session.getState(), null);
   }
 }
示例#17
0
  public void loginWithFacebook() {
    // start Facebook Login
    Session currentSession = Session.getActiveSession();
    if (currentSession == null || currentSession.getState().isClosed()) {
      Session session = new Session.Builder(this).build();
      Session.setActiveSession(session);
      currentSession = session;
    }

    // Ask for username and password
    Session.OpenRequest op = new Session.OpenRequest(this);

    op.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
    op.setCallback(null);

    List<String> permissions = new ArrayList<String>();
    permissions.add("email");
    permissions.add("user_status");
    permissions.add("friends_status");
    permissions.add("read_stream");
    op.setPermissions(permissions);

    Session session = new Session.Builder(LoginActivity.this).build();
    Session.setActiveSession(session);
    session.addCallback(
        new Session.StatusCallback() {

          // callback when session changes state
          @Override
          public void call(Session session, SessionState state, Exception exception) {
            final String accessToken = session.getAccessToken();

            if (session.isOpened()) {
              Request.executeMeRequestAsync(
                  session,
                  new Request.GraphUserCallback() {

                    public void onCompleted(GraphUser user, Response response) {
                      if (user == null) {
                        DialogHelper.showRetryDialog(
                            LoginActivity.this,
                            getString(R.string.could_not_connect_fb_account),
                            new DialogInterface.OnClickListener() {
                              public void onClick(DialogInterface dialogInterface, int i) {
                                loginWithFacebook();
                              }
                            },
                            new DialogInterface.OnClickListener() {
                              public void onClick(DialogInterface dialogInterface, int i) {
                                finish();
                              }
                            });

                      } else {
                        final String name = user.getName();
                        final String email = (String) user.getProperty("email");

                        Toast.makeText(LoginActivity.this, name + " " + email, Toast.LENGTH_LONG)
                            .show();
                        UserHelper.setCurrentUser(user, accessToken);

                        Intent i = new Intent(LoginActivity.this, RevibeActivity.class);
                        startActivity(i);
                        finish();
                      }
                    }
                  });
            }
          }
        });

    session.openForRead(op);
  }
示例#18
0
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.schoolname);

    Bundle b = this.getIntent().getExtras();
    schoolid = b.getInt("school_id");
    String schoolname = b.getString("school_name");
    email = b.getString("email");

    tvSchoolName = (TextView) findViewById(R.id.tvSchoolName);
    tvSchoolName.setTypeface(Fonts.getOpenSansBold(SchoolName.this));
    tvSchoolName.setText(schoolname);

    tvOr = (TextView) findViewById(R.id.tvOr);
    tvOr.setTypeface(Fonts.getOpenSansBold(SchoolName.this));

    bLoginFacebook = (Button) findViewById(R.id.bLoginFacebook);

    Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

    Session session = Session.getActiveSession();
    if (session == null) {
      if (savedInstanceState != null) {
        session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
      }
      if (session == null) {
        session = new Session(this);
      }
      Session.setActiveSession(session);
      if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
        session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
      }
    }

    // bLoginFacebook.setText(R.string.Log_In);
    bLoginFacebook.setOnClickListener(
        new OnClickListener() {
          public void onClick(View view) {
            onClickLogin();
          }
        });

    bRegister = (Button) findViewById(R.id.bRegister);
    bRegister.setOnClickListener(
        new Button.OnClickListener() {
          public void onClick(View v) {
            Bundle extras = new Bundle();
            extras.putInt("school_id", schoolid);
            extras.putString("email", email);

            Intent i = new Intent(getApplicationContext(), Register.class);
            i.putExtras(extras);
            startActivity(i);
          }
        });

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("com.gotoohlala.profile.ProfileSettings");
    brLogout =
        new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
            Log.d("onReceive", "Logout in progress");
            // At this point you should start the login activity and finish this one
            finish();
          }
        };
    registerReceiver(brLogout, intentFilter);
  }