1

I use firebase authentication and firebase database, i want to register every new user who login via fb and google. this is the code i use to login :

FB Login

// [START auth_with_facebook]
private void handleFacebookAccessToken(AccessToken token) {
    Log.d(TAG, "handleFacebookAccessToken:" + token);
    // [START_EXCLUDE silent]
    showProgressDialog();
    // [END_EXCLUDE]

    AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());

                    // If sign in fails, display a message to the user. If sign in succeeds

                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        Log.w(TAG, "signInWithCredential", task.getException());
                        Toast.makeText(MainActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }

                    // [START_EXCLUDE]
                    hideProgressDialog();
                    // [END_EXCLUDE]
                }
            });
}
// [END auth_with_facebook]

Google

// [START auth_with_google]
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
    // [START_EXCLUDE silent]
    showProgressDialog();
    // [END_EXCLUDE]

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());

                    // If sign in fails, display a message to the user. If sign in succeeds

                    if (!task.isSuccessful()) {
                        Log.w(TAG, "signInWithCredential", task.getException());
                        Toast.makeText(MainActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }
                    // [START_EXCLUDE]
                    hideProgressDialog();
                    // [END_EXCLUDE]
                }
            });
}
// [END auth_with_google]

all those code is in my mainActivity, so i also create auth listener :

// [START auth_state_listener]
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in, 
                // I WANT TO CHECK AND REGISTER NEW USER HERE  



                Intent home = new Intent(MainActivity.this , HomeActivity.class);
                startActivity(home);
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
            }
            // [START_EXCLUDE]

            updateUI(user);



            // [END_EXCLUDE]
        }
    };

I still don't sure how to check if the user already registered, maybe something like, check if i have nodes that have the user email, because it means the email registered before. if not registered yet, then i can call push , e.g:

String userId = mDatabase.push().getKey(); 
mDatabase.child(userId).setValue(Newuser);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Goofy_Phie
  • 671
  • 1
  • 8
  • 25
  • To ensure each user has a unique user name or email address, you store a mapping from username/email to uid in the database. See http://stackoverflow.com/questions/35243492/firebase-android-make-username-unique and http://stackoverflow.com/questions/25294478/how-do-you-prevent-duplicate-user-properties-in-firebase – Frank van Puffelen Mar 26 '17 at 15:09

1 Answers1

2

Every user in firebase has his unique ID, which you can use to identify if the user was signed in previously. After sign in you can get FirebaseUser instance:

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

And then you can get the user id:

String userId = user.getUid();

If you store users in firebase database using their ids like this

{
  "users": {
    "userId": {
      "name": "User Name",
      ...
     }
  },
 }

after login you can check if the user already exist in your db:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("users").addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  void onDataChange(DataSnapshot snapshot) {
    if (snapshot.hasChild(userId)) {
      // user already exists in db
    }
  }
});
dzikovskyy
  • 5,027
  • 3
  • 32
  • 43
  • thanks, but how if user login and registered first via email password and then try to login again via facebook ? – Goofy_Phie Mar 26 '17 at 23:29
  • When user is registered via email and then is logged in via facebook or google (via the same email), those accounts will be linked in firebase so user will be logged in with the same account. You can see it in Authentication section in firebase console, tab providers. You can also check it programatically by calling user.getProviders(), so when user is registered via email/password user.getProviders() returns you a list with one provider "password", when then user is logged in with facebook at least once those accounts will be linked and then you'll get providers "password" and "facebook.com" – dzikovskyy Mar 27 '17 at 08:00