Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 827
Chris William Avatar asked May 31 '18 01:05

Chris William


People also ask

How do I check if my phone number is registered in Firebase authentication using flutter?

After you set up admin, you can use cloud_functions package to call APIs from the firebase admin SDK and the API we'll be using is one that allows us to get a user by phone number (documentation). If the API response is a user record, we know a phone exists.


2 Answers

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);
  });
like image 103
bojeil Avatar answered Sep 23 '22 14:09

bojeil


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
                        }
                    }
                }
            });
like image 35
Elnatan Derech Avatar answered Sep 23 '22 14:09

Elnatan Derech