简体   繁体   中英

How to check if an email exists in Firebase Authentication?

I am trying to check if an email already exists in Firebase authentication, but I can find something for Java. I am trying to do something like searching in a list of emails and if that email is not in the database (emailNotExistsInDatabase(email)), then continue.

In addition to the very complete response from Alex, another possible approach is to use a Callable Cloud Function that you call from your app.

Since we use the Admin SDK in Cloud Functions you can use the getUserByEmail() method.

The function would look like:

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

exports.checkEmailExists = functions.https.onCall((data, context) => {

    return admin.auth()
        .getUserByEmail(data.email)
        .then((userRecord) => {
            return { emailExists: true }
        })
        .catch((error) => {
            throw new functions.https.HttpsError('invalid-argument', "email doesn't exist");
        });

});

With this approach you don't need a specific Firestore collection. The Admin SDK will directly query the Auth service.

Look at the doc for instructions on how to call the Callable Cloud Function from your app .


Note that the above approach is valid if you want to check if a user exists from an application (eg an Android app).

If you already use the Admin SDK from a Java based server , you just have to use the getUserByEmail() method in your server code.

There is no method inside the FirebaseAuth class that can help you check the existence of a user based on an email address. If you need that functionality you have to create it yourself. This means that 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)
          |
          --- email: "user-email@gmail.com"

To check if a user with the user-email@gmail.com already exists, then you have to perform a query that looks like this in Java:

FirebaseFirestore db = FirebaseFirestore.getInstance();
Query queryByEmail = db.collection("users").whereEqualTo("email", "user-email@gmail.com");
queryByEmail.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!
        }
    }
});

Another solution would be to use Query#count() method:

queryByEmail.count();

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

If you want to check if a given email address is associated with a user profile in Firebase, you can call the fetchSignInMethodsForEmail API .

Note that this API gives malicious users a way to perform a so-called enumeration attack, so you can actually nowadays disable fetchSignInMethodsForEmail - in which case calling it from your app would fail.

Also see:

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