How to check whether a user is authenticated or not in Firebase?

邮差的信 提交于 2019-12-24 06:42:53

问题


I have a few sign-up methods in my app as shown below:

Let's revolve the problem around Google sign-in method:
What I am doing is that when a user signs in enteringDataIntoUserNode() method is called inside signInWithCredential() method like:

    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    AuthCredential credential = 
           GoogleAuthProvider.getCredential(acct.getIdToken(), null);

    //  signing in
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {

                        //  entering default values in the database
                        enteringDataIntoUserNode();

                        Intent intent = new Intent(LoginAndSignupActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    }
                    else {
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                    }

                }
            });
}

enteringDataIntoUserNode()

private void enteringDataIntoUserNode() {
    final String currentUid = mAuth.getCurrentUser().getUid();

    //
    String deviceToken = FirebaseInstanceId.getInstance().getToken();
    final String userName = mAuth.getCurrentUser().getDisplayName();
    String imageUrl = mAuth.getCurrentUser().getPhotoUrl().toString();
    String userStatus = "Hi there! How is it going?";

    //  inserting data in key-value pair
    usersReference.child(currentUid).child("user_name").setValue(userName);
    usersReference.child(currentUid).child("user_status").setValue(userStatus);
    usersReference.child(currentUid).child("user_image").setValue(imageUrl);
    usersReference.child(currentUid).child("device_token").setValue(deviceToken);

    //  when this last value will be inserted then, making an intent to MainActivity
    usersReference.child(currentUid).child("user_thumb_image").setValue(imageUrl)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if(task.isSuccessful()){
                        Log.d(TAG, "onComplete: Data insertion for the new user is successful ");
                    }
                }
            });
}

enteringDataIntoUserNode() method is simply passing some default data to the database every time a user signs in. But if a user change its details like image or username etc. and sign out and again sign in through Google sign in method then again enteringDataIntoUserNode() method will be called and user details would be overwritten with the default ones.

My question is that is there any way to check whether a user is signing in for the first time or not during the Google sign in so that in the latter case I can skip calling enteringDataIntoUserNode() method and prevent overwriting of data. Same thing I want to acheive during Facebook and Phone Number sign in.


回答1:


If you check if the user logs in for the first time, it's the same thing if you want to check if a user is new. So to solve this, we can simply call the isNewUser() method in the OnCompleteListener.onComplete callback like this:

OnCompleteListener<AuthResult> completeListener = new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
        if (task.isSuccessful()) {
            boolean isNewUser = task.getResult().getAdditionalUserInfo().isNewUser();
            if (isNewUser) {
                Log.d("TAG", "The user is new!");
            } else {
                Log.d("TAG", "The user is not new!");
            }
        }
    }
};

For more informations, please see the official documentation.




回答2:


You could check when the account was created with:

task.getResult().getUser().getMetadata().getCreationTimestamp()

See the reference docs.

But a common approach is also to check if the user already exists in the database using a transaction.



来源:https://stackoverflow.com/questions/51443538/how-to-check-whether-a-user-is-authenticated-or-not-in-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!