简体   繁体   中英

Facebook/Android - how to check whether the user has already been registered, and now just log them in

I am having trouble implementing Facebook login/register with Android. The documentation is not sufficient, and their use case is strange (all they talk about is fragments there and this gets attention away from the main subject)

What I have created is working login(registration) but If I dont have a check whether the user is already logged in, so the app tries to insert them into the db anew, resulting in an error.

Also I dont know what uiHelper is for so I've completely removed it from my code.

My question is how to check whether the user has already been registered via Facebook and now just log them in.

EDIT: what Im trying to say is that the user is not logged in in both cases, but in one of the cases, they have already registered via fb, and I want to just log them in. In the other case they havent registered via fb and its their first approach, so I want to register them in the database and log them in (I've already accomplished the latter)

@Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.authButton) {
            OpenRequest openrequest = new OpenRequest(this).setPermissions(Arrays.asList("basic_info", "email", "user_likes", "user_status"));
            Session session = new Session(Login.this);
            session.openForRead(openrequest);
}

private Session.StatusCallback callback = new Session.StatusCallback() {
    @Override
    public void call(Session session, SessionState state, Exception exception) {
        onSessionStateChange(session, state, exception);
    }
};

private void onSessionStateChange(Session session, SessionState state, Exception exception) {

    if (state.isOpened()) {
         makeMeRequest(session);
    } else if (state.isClosed()) {

        System.out.println("closed"); //debugging
        Session sessionw = new Session(this);
        Session.setActiveSession(sessionw);
        sessionw.openForRead(new Session.OpenRequest(this).setCallback(callback).setPermissions(Arrays.asList("basic_info", "email", "user_likes", "user_status")));
    }
}


private void makeMeRequest(final Session session) {
    // Make an API call to get user data and define a 
    // new callback to handle the response.
    Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
        @Override
        public void onCompleted(GraphUser user, Response response) {
            // If the response is successful
            if (session == Session.getActiveSession()) {
                if (user != null) {
                    userFBId = user.getId();
                    userName = user.getName();
                    userEmail = (String) user.asMap().get("email");
                    userSex = (String) user.getProperty("gender");
                    userFacebookAvatar = "http://graph.facebook.com/"+user.getId()+"/picture?type=square";

                    new RegisterFacebookUser(Login.this, Login.this, userName, userEmail, userSex, userFacebookAvatar).execute(); //this is an async task that inserts the user in the db
                }
            }
            if (response.getError() != null) {
                System.out.println(response.getError().toString());
            }
        }
    });
    request.executeAsync();
} 


@Override 
public void OnFacebookUserRegisteredSuccess(int userId) {
    editor = sharedPrefs.edit();
    editor.putBoolean("userLoggedInState", true);
    editor.putBoolean("userHasRegisteredViaFacebook", true);
    editor.putInt("currentLoggedInUserId", userId);
    editor.putString("userFBId", userFBId);
    editor.commit();
    Intent signupSuccessHome = new Intent(this, Home.class);
    startActivity(signupSuccessHome);
    finish();

}

@Override
public void OnFacebookUserRegisteredFailure() {

    toastMaker.toast(net.asdqwe.activities.Login.this, Configurationz.ErrorMessages.FACEBOOK_LOGIN_FAILURE, Toast.LENGTH_LONG);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REAUTH_ACTIVITY_CODE) {
       Session.getActiveSession().onActivityResult(Login.this, requestCode, resultCode, data);
    } else {

        Session session = Session.getActiveSession();
        int sanitizedRequestCode = requestCode % 0x10000;
        session.onActivityResult(this, sanitizedRequestCode, resultCode, data);

    }
}

You shouldn't be relying on your own preference to determine if the user has previously registered and therefore only "log them in". Facebook allows users to register for an app but the user may in the future unregister or delete your app from their console. Following which Facebook will reset the permission token it sent to your app, and any activity such as posting on the user's behalf will be rejected.

So to answer your question, just do the flow you are doing for registration and login. If the user has already registered, Facebook will popup some permission UI flow where the user doesn't have to do any action (since all permissions were already granted). And you will get back the session token in your app. Update this session token in your app and use this in the future for all requests on behalf of the user.

Note: I think you are using an older version of the Facebook SDK. You should upgrade to the latest (3.6). They have fixed quite a few registration/ login issues and your users will thank you much.

To check whether the user session is active and also if he has the required permissions to perform an action you can do something like that:

public static boolean hasFacebookPermissions(List<String> permissions) {
    Session activeSession = Session.getActiveSession();
    return activeSession != null && activeSession.isOpened() && activeSession.getPermissions().containsAll(permissions);
}

In your code:

    if (id == R.id.authButton) {
        if(hasFacebookPermissions(Arrays.asList("basic_info", "email", "user_likes", "user_status")) {
            // The user is already logged in
            Request request = Request.newMeRequest(Session.getActiveSession(), new Request.GraphUserCallback() {
                @Override
                    public void onCompleted(GraphUser user, Response response) {
                        // If the response is successful
                        if (user != null) {
                            userFBId = user.getId();
                            userName = user.getName();
                            userEmail = (String) user.asMap().get("email");
                            userSex = (String) user.getProperty("gender");
                            userFacebookAvatar = "http://graph.facebook.com/"+user.getId()+"/picture?type=square";
                            // Now you can start your other activity and pass the user infos

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM