7

I'm trying to login from Facebook and Google API, the Google API works fine, the problem arises with Facebook login, everything is setup on the Facebook developers console and my app is live as well.

The problem is whenever user clicks on the login button (which is a customized ImageButton) the ProgressBar shows up and then it goes away and the app is still on the same activity without user being logged in.

The complete code for that activity is:

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_opening);

    progressDialog = new ProgressDialog(this);
    mAuth = FirebaseAuth.getInstance();
    Auth = FirebaseAuth.getInstance();
    if (mAuth.getCurrentUser() != null) {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    GoogleSignInOptions gso = new GoogleSignInOptions
        .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestIdToken(getString(R.string.default_web_client_id))
        .requestEmail()
        .build();

    mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

    Google = (ImageView) findViewById(R.id.googleSignin);
    Google.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            SIGN_IN_REQUEST = 1;
            signIn();
            progressDialog.setMessage("Loading...");
            progressDialog.setCancelable(false);
            progressDialog.show();
        }
    });

    callbackManager = CallbackManager.Factory.create();

    Facebook = (ImageView) findViewById(R.id.facebookSignin);
    Facebook.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            SIGN_IN_REQUEST = 2;
            progressDialog.show();
            progressDialog.setCancelable(false);
            progressDialog.setMessage("Loading...");

            LoginManager.getInstance().logInWithReadPermissions(opening.this, Arrays.asList("email", "public_profile"));
            LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {
                    Log.d(TAG2, "facebook:onSuccess:" + loginResult);
                    handleFacebookAccessToken(loginResult.getAccessToken());
                    setFbData(loginResult);
                    progressDialog.dismiss();
                }

                @Override
                public void onCancel() {
                    Log.d(TAG2, "facebook:onCancel");
                    Toast.makeText(getApplicationContext(),"facebook:oncancel",Toast.LENGTH_LONG).show();
                    progressDialog.dismiss();
                }

                @Override
                public void onError(FacebookException error) {
                    Log.d(TAG2, "facebook:onError", error);
                    Toast.makeText(getApplicationContext(),"facebook:onError",Toast.LENGTH_LONG).show();
                    progressDialog.dismiss();
                }
            });
        }
    });

    Email = (ImageView)findViewById(R.id.emailLogin);
    Email.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getApplicationContext(), SignIn.class);
            startActivity(intent);
            finish();
        }
    });

    AlreadyLoggedin = (ImageView)findViewById(R.id.Already);
    AlreadyLoggedin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getApplicationContext(), login.class);
            startActivity(intent);
            finish();
        }
    });

}

private void signIn(){
    Intent signInIntent = mGoogleSignInClient.getSignInIntent();
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);

    if (SIGN_IN_REQUEST == 1) {
        if (requestCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                GoogleSignInAccount account = task.getResult(ApiException.class);
                firebaseAuthWithGoogle(account);
            } catch (ApiException e) {
                Toast.makeText(getApplicationContext(), "Google sign in Failed", Toast.LENGTH_LONG).show();
                String s1 = task.getException().getMessage();
                Toast.makeText(getApplicationContext(),"" + s1,Toast.LENGTH_LONG).show();
                progressDialog.dismiss();
                String s = task.getException().getMessage();
                Toast.makeText(getApplicationContext(),"ErrorCode: " + s,Toast.LENGTH_LONG).show();
            }
        }
    } else if (SIGN_IN_REQUEST == 2){
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }
}

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = mAuth.getCurrentUser();
                        updateUI(user);
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Snackbar.make(findViewById(R.id.snake), "Authentication Failed.", Snackbar.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                        updateUI(null);
                    }

                    // ...
                }
            });
}

@Override
protected void onStart() {
    super.onStart();
    FirebaseUser currentUser = mAuth.getCurrentUser();
    updateUI(currentUser);
}

private void updateUI(FirebaseUser user) {
    /*
        Intent intent = new Intent(opening.this, MainActivity.class);
        startActivity(intent);
        finish();
    */
    progressDialog.dismiss();

    if (SIGN_IN_REQUEST == 1) {

        GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
        if (acct != null) {
            String personName = acct.getDisplayName();
            String personGivenName = acct.getGivenName();
            String personFamilyName = acct.getFamilyName();
            String personEmail = acct.getEmail();
            String personId = acct.getId();
            Uri personPhoto = acct.getPhotoUrl();

            String uid = mAuth.getCurrentUser().getUid();

            Intent intent = new Intent(opening.this, userInf.class);
            intent.putExtra("UID", uid);
            intent.putExtra("Phone", PhoneNumber);
            intent.putExtra("Name", personName);
            startActivity(intent);
            finish();

        }
    } else if (SIGN_IN_REQUEST == 2) {

        if (user != null) {
            progressDialog.dismiss();
            Intent intent = new Intent(opening.this, userInf.class);
            intent.putExtra("Phone", PhoneNumber);
            intent.putExtra("Name", Name);
            startActivity(intent);
            finish();
        } else {
            Toast.makeText(getApplicationContext(),"updating error",Toast.LENGTH_LONG).show();
        }
    }
}

private void setFbData(final LoginResult loginResult){
    GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
            new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject object, GraphResponse response) {
                    try {
                        String first_name = response.getJSONObject().getString("first_name");
                        String last_name = response.getJSONObject().getString("last_name");

                        Name = String.valueOf(first_name + " " + last_name);
                    } catch (JSONException e){
                        e.printStackTrace();
                    }
                }
            });
}

private void handleFacebookAccessToken(AccessToken token) {

    Log.d(TAG, "handleFacebookAccessToken:" + token);
    Toast.makeText(getApplicationContext(),"HandelingRequest",Toast.LENGTH_LONG).show();

    AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
    Auth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = mAuth.getCurrentUser();
                        progressDialog.dismiss();
                        updateUI(user);
                    } else {
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Toast.makeText(opening.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                        updateUI(null);
                    }
                }
            });
}}

The log out is something like this:

D/FACELOG: facebook:onSuccess:com.facebook.login.LoginResult@d573369
D/GoogleActivity: handleFacebookAccessToken:{AccessToken token:ACCESS_TOKEN_REMOVED permissions:[public_profile, email]}
W/BiChannelGoogleApi: [FirebaseAuth: ] getGoogleApiForMethod() returned Gms: com.google.firebase.auth.api.internal.zzal@6703527
I/FirebaseAuth: [FirebaseAuth:] Loading module via FirebaseOptions.
                [FirebaseAuth:] Preparing to create service connection to gms implementation

I've been looking around for this from quite some time and have not found anything which solves my problem.

Martin Zeitler
  • 1
  • 19
  • 155
  • 216
jp singh
  • 324
  • 2
  • 13
  • 1
    is there any log message by your authresult handler? ("signInWithCredential:success/failure" in handleFacebookAccessToken()) – lenhuy2106 Oct 23 '18 at 12:54
  • 1
    @lenhuy2106..... Nope....this is why I'm confused......there is no such message in log which suggests whether sign was successfully or not – jp singh Oct 23 '18 at 12:55
  • 1
    try log the token itself: Log.d(TAG, "handleFacebookAccessToken:" + token.getToken()) – lenhuy2106 Oct 23 '18 at 13:00
  • 1
    I've done that..... I've added last few lines of log....and it shows ACCESS_TOKEN_REMOVED – jp singh Oct 23 '18 at 13:06
  • it shows that because you can't log the AccessToken instance, but only its token field, see https://stackoverflow.com/questions/18307535/accesstoken-tokenaccess-token-removed-in-facebook-android-sdk You may debug better with the actual token being corrupted or not. – lenhuy2106 Oct 23 '18 at 13:10
  • Do you use a real device or a emulator? what google play services version do you use? possible duplicate: https://stackoverflow.com/questions/37375983/firebase-android-auth-object-no-callbacks-firing – lenhuy2106 Oct 23 '18 at 13:22
  • I'm testing it on a real device....and i have also updated google play services......but i don't think it could be due to google play services.....coz I'm using Facebook sdk....and i guess that is totally different from google (please correct me if I'm wrong) – jp singh Oct 23 '18 at 17:51
  • https://chat.stackoverflow.com/rooms/182381/discussion-between-lenhuy2106-and-jp-singh – lenhuy2106 Oct 23 '18 at 18:59
  • are you testing on a device with facebook installed? if not, do you use webviews in the app? – stallianz Oct 24 '18 at 13:43
  • Do the problem occur even after freshly installing the app? – Kruti Parekh Oct 25 '18 at 14:35
  • @stallianz yes i'm testing it on a device with facebook installed. – jp singh Oct 26 '18 at 16:16
  • @parekhkruti26 yes, the problem is still there, i've tested it on debug as well as release apks, but the problem is still the same. – jp singh Oct 26 '18 at 16:17
  • @lenhuy2106 i've tried printing the access token in the log, and it returns a huge key, but I'm not sure whether this token is broken or not. – jp singh Oct 26 '18 at 16:35

5 Answers5

1

I am using the following method for fb login, As per our knolwedge, we have tested all the boundary conditions & its working fine for us now and never faced any challenge yet.

//on click of fb button
        private void handleFBLogin() {
                AccessToken accessToken = AccessToken.getCurrentAccessToken();
                LoginManager.getInstance().logOut();
                boolean isLoggedIn = accessToken != null && !accessToken.isExpired();
                LoginManager.getInstance().logInWithReadPermissions(ActivityLogin.this, Arrays.asList("public_profile", "email"));
                LoginManager.getInstance().registerCallback(callbackManager,
                        new FacebookCallback<LoginResult>() {
                            @Override
                            public void onSuccess(final LoginResult loginResult) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        setFacebookData(loginResult, d);
                                    }
                                });
                            }

                            @Override
                            public void onCancel() {
    Toast.makeText(getApplicationContext(), "Canceled login ", Toast.LENGTH_SHORT); toast.show();

                            }

                            @Override
                            public void onError(FacebookException exception) {
                                d.dismiss();
                                if (exception instanceof FacebookAuthorizationException) {
                                    if (AccessToken.getCurrentAccessToken() != null) {
                                        LoginManager.getInstance().logOut();
                                        handleFBLogin();
                                        return;
                                    }
                                }
    Toast.makeText(getApplicationContext(), "ERROR " + exception.toString(), Toast.LENGTH_SHORT); toast.show();

                                PackageInfo info;
                                try {
                                    info = getPackageManager().getPackageInfo([your package name], PackageManager.GET_SIGNATURES);
                                    for (Signature signature : info.signatures) {
                                        MessageDigest md;
                                        md = MessageDigest.getInstance("SHA");
                                        md.update(signature.toByteArray());
                                        String something = new String(Base64.encode(md.digest(), 0));
                                        //String something = new String(Base64.encodeBytes(md.digest()));
                                        Log.e("hash key", something);
                                    }
                                } catch (Exception e1) {
                                    Log.e("name not found", e1.toString());
                                }
                            }
                        });
            }


    private void setFacebookData(final LoginResult loginResult) {
            GraphRequest request = GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {
                            try {
                                final String firstName = response.getJSONObject().getString("first_name");
                                String lastName = response.getJSONObject().getString("last_name");
                                String id = response.getJSONObject().getString("id");
                                String email = null;
                                if (response.getJSONObject().has("email"))
                                    email = response.getJSONObject().getString("email");
                                //put your code here
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id,email,first_name,last_name,gender");
            request.setParameters(parameters);
            request.executeAsync();
        }
aanshu
  • 1,602
  • 12
  • 13
  • As you provided the bounty to the above answer. If you think the above solution could help other developers, would you please mark it an answer. – aanshu Oct 31 '18 at 18:01
0

from this link it is clear that the access token cannot be see in logcat. thats why you are seeing token:ACCESS_TOKEN_REMOVED

stallianz
  • 176
  • 1
  • 17
  • even this is not working, problem is still the same, it shows access token removed and thats where everything stops – jp singh Oct 26 '18 at 16:15
  • 'facebook:onSuccess:com.facebook.login.LoginResult@300f4fc handleFacebookAccessToken:{AccessToken token:ACCESS_TOKEN_REMOVED permissions:[public_profile, email]}' this is the last printed lines on log and then nothing shows up and i've also checked on log, the user isn't logged in – jp singh Oct 26 '18 at 16:25
  • looks like this is Auth.signInWithCredential(credential) deprecated, I recommend using Auth.signInAndRetrieveDataWithCredential – stallianz Oct 26 '18 at 16:42
  • I've just now tried [this link](https://stackoverflow.com/a/38570546/9113054) and I'm quite sure what I'm getting is the access token but still my problem has not been solved because the problem is still there – jp singh Oct 26 '18 at 16:46
  • did you configure your firebase console? – stallianz Oct 26 '18 at 16:49
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/182604/discussion-between-stallianz-and-jp-singh). – stallianz Oct 26 '18 at 16:54
0

the reason is, that you are mixing up Auth and mAuth in method handleFacebookAccessToken(AccessToken token).

the problem already introduces itself onCreate():

mAuth = FirebaseAuth.getInstance();
Auth = FirebaseAuth.getInstance();

remove Auth and use the instance called mAuth everywhere.

Martin Zeitler
  • 1
  • 19
  • 155
  • 216
0

Try calling intent in onSuccess() method

@Override
    public void onSuccess(LoginResult loginResult) {
        Log.d(TAG2, "facebook:onSuccess:" + loginResult);
        handleFacebookAccessToken(loginResult.getAccessToken());
        setFbData(loginResult);
        progressDialog.dismiss();
        //call activity here
        startActivity(new Intent(MainActivity.class));
        }
PradyumanDixit
  • 2,372
  • 2
  • 12
  • 20
0

In the debug mode you have to enable the logging for access token. So Add this lines

if (BuildConfig.DEBUG) {
FacebookSdk.setIsDebugEnabled(true);
FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
}
LoginManager.getInstance().registerCallback(callbackManager, new 
FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {

        final GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
            @Override
            public void onCompleted(JSONObject object, GraphResponse response) {
                try {
                    if (object.has("id")) {
                        handleSignInResultFacebook(object);   // Parse the json object for user details
                    } else {
                        Logger.e("FBLOGIN_FAILD", String.valueOf(object));
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    dismissDialogLogin();
                }
            }
        });
   final Bundle parameters = new Bundle();
        parameters.putString("fields", "name,email,id,picture.type(large)");
        request.setParameters(parameters);
        request.executeAsync();

    }

    @Override
    public void onCancel() {
        Logger.e("FBLOGIN_FAILD", "Cancel");
    }

    @Override
    public void onError(FacebookException error) {
        Logger.e("FBLOGIN_FAILD", "ERROR", error);
    }
});
gStephin
  • 332
  • 3
  • 20