简体   繁体   中英

how to check if phone exists in firebase auth

hey I try to check if the phone number that user is insert is exist in my firebase auth (LoginActivity) I try in this way


String phoneNumber = "+1234567890";

mAuth.fetchSignInMethodsForEmail(phoneNumber)
        .addOnCompleteListener(new OnCompleteListener<SignInMethodQueryResult>() {
            @Override
            public void onComplete(@NonNull Task<SignInMethodQueryResult> task) {
                if (task.isSuccessful()) {
                    SignInMethodQueryResult result = task.getResult();
                    List<String> signInMethods = result.getSignInMethods();
                    if (signInMethods.contains("phone")) {
                        // Phone number is already in use in Firebase Auth
                    } else {
                        // Phone number is not in use in Firebase Auth
                    }
                } else {
                    // An error occurred
                }
            }
        });

and when it comes to this function the debugger jump for it and don't doing anything.addOnCompleteListener(new OnCompleteListener() {

I try with firebase sdk admin and it also doesn't works can anyone know how to solve this?

There are three ways in which you can solve this problem. Two options are on the client, using Java code, and another one using Admin SDK.

Solution 1

When a user signs in for the first time into your app, then save user data in Firestore using a schema that looks like this:

db
|
--- users (collection)
     |
     --- $uid (document)
          |
          --- phoneNumber: "+1234567890"

To check if a user with the +1234567890 already exists, then you have to perform a query that looks like this in Java:

FirebaseFirestore db = FirebaseFirestore.getInstance();
Query queryPhoneNumber = db.collection("users").whereEqualTo("phoneNumber", "+1234567890");
queryPhoneNumber.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (QueryDocumentSnapshot document : task.getResult()) {
                if (document.exists()) {
                    Log.d(TAG, "User already exists.");
                } else {
                    Log.d(TAG, "User doesn't exist.");
                }
            }
        } else {
            Log.d(TAG, task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});

Solution 2

Another more elegant and easy solution would be to use Query#count() method:

queryPhoneNumber.count();

If the result is > 0 then it means that the user already exists, otherwise it doesn't exist.

Solution 3

The last solution would be to use a Callable Cloud Function that can be called from your app . Because we use the Admin SDK in Cloud Functions you can call the getUserByPhoneNumber() method. In code it will look like this:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.checkPhoneNumberExists = functions.https.onCall((data, context) => {
    return admin.auth()
        .getUserByPhoneNumber(data.phoneNumber)
        .then((userRecord) => {
            return { phoneNumber: true }
        })
        .catch((error) => {
            throw new functions.https.HttpsError('invalid-argument', "phoneNumber doesn't exist");
        });

});

Using this approach, there is no need to save user data in Firestore. The Admin SDK will directly query the FirebaseAuth service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM