簡體   English   中英

如何檢查Firebase認證中是否存在email?

[英]How to check if an email exists in Firebase Authentication?

我正在嘗試檢查 email 是否已存在於 Firebase 身份驗證中,但我可以找到 Java 的內容。我正在嘗試執行類似搜索電子郵件列表的操作,如果 email 不在數據庫中 (emailNotExistsInDatabase(email)) ,然后繼續。

除了來自 Alex 的非常完整的響應之外,另一種可能的方法是使用您從應用程序調用的Callable Cloud Function

由於我們在 Cloud Functions 中使用 Admin SDK,您可以使用getUserByEmail()方法。

function 看起來像:

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");
        });

});

使用這種方法,您不需要特定的 Firestore 集合。 Admin SDK會直接查詢Auth服務。

查看文檔以獲取有關如何從您的應用調用 Callable Cloud Function 的說明。


請注意,如果您想檢查應用程序(例如 Android 應用程序)中的用戶是否存在,上述方法是有效的。

如果您已經從基於 Java 的服務器使用 Admin SDK ,則只需在服務器代碼中使用getUserByEmail()方法。

FirebaseAuth class 中沒有任何方法可以幫助您檢查基於 email 地址的用戶是否存在。 如果您需要該功能,則必須自己創建。 這意味着當用戶首次登錄您的應用時,使用如下所示的架構將用戶數據保存在Firestore中:

db
|
--- users (collection)
     |
     --- $uid (document)
          |
          --- email: "user-email@gmail.com"

要檢查具有user-email@gmail.com的用戶是否已經存在,那么您必須在 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!
        }
    }
});

另一種解決方案是使用Query#count()方法:

queryByEmail.count();

如果結果 > 0 則表示該用戶已經存在,否則不存在。

如果你想檢查給定的 email 地址是否與 Firebase 中的用戶配置文件相關聯,你可以調用fetchSignInMethodsForEmail API

請注意,此 API 為惡意用戶提供了一種執行所謂的枚舉攻擊的方法,因此您現在實際上可以禁用fetchSignInMethodsForEmail - 在這種情況下,從您的應用程序調用它會失敗。

另見:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM