0

Hello I want to know how can I access user email while authenticating a user through Github in my android App. I am using firebase and android studio. Please note that I cannot use user.getEmail in onSuccesslistner because I am also using Google authentication, which throws exception that email already exist and pending task method works for first time only. Basically I want to use setScopes to retrieve the user Email. I have to get Email and check if user exist in my database in simply logged in user.

Here is my Code:

    public void git_login(View view)
        {
            SignInWithGithubProvider(
                    OAuthProvider.newBuilder("github.com")
                            .setScopes(
                                   new ArrayList<String>()
                                    {
                                        {
                                            add("user:email");
                                        }
                                    }).build()
            );
        }
    
        private void SignInWithGithubProvider(OAuthProvider login)
        {
            Task<AuthResult> pendingResultTask= mAuth.getPendingAuthResult();
            if (pendingResultTask!=null)
            {
                // There's something already here! Finish the sign-in for your user.
                pendingResultTask
                        .addOnSuccessListener(
                                new OnSuccessListener<AuthResult>() {
                                    @Override
                                    public void onSuccess(AuthResult authResult) {
                                        Toast.makeText(getApplicationContext(), "User Exist" + authResult, Toast.LENGTH_SHORT).show();
                                        // User is signed in.
                                        // IdP data available in
                                        // authResult.getAdditionalUserInfo().getProfile().
                                        // The OAuth access token can also be retrieved:
                                        // authResult.getCredential().getAccessToken().
                                    }
                                })
                        .addOnFailureListener(
                                new OnFailureListener() {
                                    @Override
                                    public void onFailure(@NonNull Exception e) {
                                        // Handle failure.
                                    }
                                });
            }
            else {
                // There's no pending result so you need to start the sign-in flow.
                // See below.
                mAuth.startActivityForSignInWithProvider(this , login).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e)
                    {
    
                        if (e.toString().equals("com.google.firebase.auth.FirebaseAuthUserCollisionException: An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address."))
                        {
                            showDialogAlert();
                        }
                    }
                }).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
                    @Override
                    public void onSuccess(AuthResult authResult) {
                        FirebaseUser user = mAuth.getCurrentUser();
                        Toast.makeText(getApplicationContext(), "Login" + user.getUid() +"\n"+user.getEmail(), Toast.LENGTH_SHORT).show();
                        userNameForDb = user.getDisplayName();
                        userImageForDb = String.valueOf(user.getPhotoUrl());
                        userEmailForDb = user.getEmail();
                        Toast.makeText(CreateNewAccountActivity.this, "Account added to Firebase: " +userNameForDb+"\n"+userEmailForDb+"\n"+userTokenForDb, Toast.LENGTH_SHORT).show();
                        saveDataToDb(userNameForDb , userEmailForDb , userTokenForDb);
                    }
                });
    
            }
        }
```
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Have you tried to get the email address from the `authResult` object? – Alex Mamo Mar 30 '21 at 12:06
  • yes I tried but due some reasons this method is not running. May be it run only first time But I need to get user email several time when he click on github auth button – servicez point Mar 30 '21 at 12:12

1 Answers1

0

I want to know how can I access user email while authenticating a user through Github

The simplest solution I can think of is once you are successfully authenticated, you can get the email address from the "userInfo" object like in the following lines of code:

FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser != null) {
    for (UserInfo userInfo : firebaseUser.getProviderData()) {
        if (userInfo.getProviderId().equals("github.com")) {
            Log.d(TAG, "User is signed in with Github");
            Log.d(TAG, "email: " + userInfo.getEmail());
        }
    }
}

The output in the logcat will be the email address that was used by the user for the authentication process.

Edit:

It's true, if the user is already registered with a Gmail account, you'll get an Exception that says that such an account is already there. So you need to use for authentication Google credentials.

I actually want to get the user id in this case and want to check it in my database which is my local server that this email exists or not.

There is no need for that because you can handle the Exception, and indicate to the user that a Google account is already there, and then simply use Google credentials for authentication. If there is no Exception, is obvious that the user doesn't exist yet.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • I already mention that if user is already registered with his google account in this case firebase will throw exception user already exist with different provider in this case current user will be null. I actually want to get user id in this case and want to check it in my database which is my local server that this email exist or not – servicez point Mar 30 '21 at 12:41
  • For that, please check my updated answer. – Alex Mamo Mar 30 '21 at 12:54
  • well you are right but i have some requirements from my seniors. that i have to get email and check email in my database which is mysql database backend php that if this email exist in database i have to redirect user from Login to Home Activity. Well i know we can get email through Scopes but i dont know how – servicez point Mar 31 '21 at 09:53
  • To check the email address for existence on an SQL server sounds like another task, which is completely different than searching data in a Firebase database. However, once you've checked that, you can simply redirect the user to the MainActivity. – Alex Mamo Mar 31 '21 at 10:13
  • oh dear i did not got solution solution i want email. When i redirect user to MainActivity i have to get user data i.e.. name , dob which is stored in database and i have to compare email to get all data – servicez point Mar 31 '21 at 13:00
  • That's again obviously another issue that is not related to the initial question. If you have a hard time implementing the search in your SQL database, please post a new question using its own [MCVE](https://stackoverflow.com/help/mcve), so you can get appropriate help. – Alex Mamo Mar 31 '21 at 13:21
  • public void git_login(View view) { SignInWithGithubProvider( OAuthProvider.newBuilder("github.com") .setScopes( new ArrayList() { { add("user:email"); } }).build() ); } – servicez point Apr 02 '21 at 10:50
  • can you make some logic to get user id from this peace of code – servicez point Apr 02 '21 at 10:51
  • This should be considered another question that cannot be answered in a comment or using only the data above. Besides that, it's beyond the scope of this question. So in order to follow the rules of this community, please post a new question using its own [MCVE](https://stackoverflow.com/help/mcve), so I and other Firebase developers can help you. – Alex Mamo Apr 02 '21 at 11:33