How to check if a user already exists in firebase during phone auth

不羁的心 提交于 2020-06-01 05:56:10

问题


I'm trying to create an app that only uses phone authorization from firebase. Since the login/signup is done through same process, which is verifying the sent code. How can i check if a user already exists in firebase? I need this to show them appropriate User Interface.


回答1:


Right now, the only way to do that is via the Firebase Admin SDK. There is an API to lookup a user by phone number.

admin.auth().getUserByPhoneNumber(phoneNumber)
  .then(function(userRecord) {
    // User found.
  })
  .catch(function(error) {
    console.log("Error fetching user data:", error);
  });



回答2:


You can check whether user already exist in Firebase by compare it metadata. see code example:

PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.getCredential(verificationId, smsCode);
            FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential).addOnCompleteListener(PhoneLoginEnterCodeActivity.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
                        FirebaseUser user = task.getResult().getUser();
                        long creationTimestamp = user.getMetadata().getCreationTimestamp();
                        long lastSignInTimestamp = user.getMetadata().getLastSignInTimestamp();
                        if (creationTimestamp == lastSignInTimestamp) {
                            //do create new user
                        } else {
                           //user is exists, just do login
                        }
                    } else {
                        // Sign in failed, display a message and update the UI
                        if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                            // The verification code entered was invalid
                        }
                    }
                }
            });


来源:https://stackoverflow.com/questions/50615308/how-to-check-if-a-user-already-exists-in-firebase-during-phone-auth

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