Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test whether this is the first time the facebook login was called with firebase

For the email and password authentication in firebase we have both "register" and "log in" functions, but for the log in with Facebook we only have the login(or am i'm wrong?)
I'm trying to determine whether this is the first time the user have connected to the application with this facebook account, and if so, add it to the database as well.

this is my current code, becuase firebase is an async database, this mechanizem does not work

@Override
protected void onCreate (Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_customer);

    mLoginButton = (LoginButton) findViewById(R.id.login_button);
    mLoginButton.setVisibility(View.GONE);

    mCallbackManager = CallbackManager.Factory.create();
    mLoginButton.setReadPermissions("email", "public_profile");
    mLoginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            handleFacebookAccessToken(loginResult.getAccessToken());
            Toast.makeText(MainCustomerActivity.this, "Login Success", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel() {
            Toast.makeText(MainCustomerActivity.this, "Cancelled", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(FacebookException error) {
            Log.d(TAG, error.toString());
            Toast.makeText(MainCustomerActivity.this, "Error!", Toast.LENGTH_SHORT).show();
        }
    });

    private void handleFacebookAccessToken (AccessToken token) {
        Log.d(TAG, "handleFacebookAccessToken:" + token);

        AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
        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");
                        currentUser = mAuth.getCurrentUser();
                        testRegisterNewUser();
                        updateUI();
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Toast.makeText(MainCustomerActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                        //TODO: HANDLE BAD LOGIN
                    }
                    // ...
                }
            });
    }

    private void testRegisterNewUser () {
        String uid = currentUser.getUid();

        mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(uid);
        mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                testRegisterUserName = (String) dataSnapshot.getValue();

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        //this is where I want to find whether this uid is already in the database
        if (testRegisterUserName != null) {
            return;
        } else {
            //this is where I want to store to the database

Can I somehow query the handleFacebookAccessToken to determine if it's the first time the user logged in to the server?

like image 512
DsCpp Avatar asked Mar 22 '18 17:03

DsCpp


People also ask

How to check if a user logged in for the first time in Firebase?

To check if it's the first time user logs in, simply call the AdditionalUserInfo. isNewUser() method in the OnCompleteListener.

Does Firebase work with Facebook?

You can let your users authenticate with Firebase using their Facebook accounts by integrating Facebook Login into your app.

Which method will you call to logout a user from Firebase?

According to documentation, I force a user to sign out with the method signOut() . This is what I have tried: var rootRef = firebase. database().

How can I get user details from Firebase?

If the user login with a custom "email/password" you don't know anything else about that user (apart from the unique user id). If a user login with Facebook, or with Google sign in, you can get other information like the profile picture url. It is explained here: firebase.google.com/docs/auth/android/… .


1 Answers

You can use the API isNewUser() for when the sign in process is complete. See the docs.

Returns whether the user is new or existing.

So your code (only the onComplete part) would look like this now:

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");
        currentUser = mAuth.getCurrentUser();
        boolean isNewUser = task.getResult().getAdditionalUserInfo().isNewUser();
        if(isNewUser){
              testRegisterNewUser();
        }
        updateUI();
    } else {
        // If sign in fails, display a message to the user.
        Log.w(TAG, "signInWithCredential:failure", task.getException());
        Toast.makeText(MainCustomerActivity.this, "Authentication failed.",
                Toast.LENGTH_SHORT).show();
        //TODO: HANDLE BAD LOGIN
    }
    // ...
}
like image 129
Levi Moreira Avatar answered Sep 30 '22 06:09

Levi Moreira