如何在Firebase中检查用户是否存在?

22

我的身份验证功能终于能够创建用户并进行登录和登出了。但现在,我想实现一个功能,检查用户是否已经存在于Firebase中。我已经查过了,但似乎找不到确切的答案。

比如说,如果我的电子邮件地址是abc12@gmail.com,另一个人也试图使用相同的电子邮件地址注册,我该如何告诉他们这个邮箱已经被注册了呢?

login(e) {
    e.preventDefault();

    fire.auth().signInWithEmailAndPassword(this.state.email, this.state.password)
        .then((u) => {
        }).catch((error) => {
        console.log(error);
    });
}

signup(e) {
    e.preventDefault();

    fire.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
        .then((u) => {
        }).catch((error) => {
        console.log(error);
    });
}

2
重复的问题? https://dev59.com/aFcP5IYBdhLWcg3wTIMt - Chris Hawkes
2
可能是Firebase检测用户是否存在的重复问题。 - Mathews Sunny
4个回答

36
调用createUserWithEmailAndPassword方法返回的错误对象有一个code属性。根据文档,错误的codeauth/email-already-in-use,表示该邮件地址已被使用。
至少可以使用条件语句如if/elseswitch来检查该code并向用户显示/记录/分发等信息或代码。
fire.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
  .then(u => {})
  .catch(error => {
     switch (error.code) {
        case 'auth/email-already-in-use':
          console.log(`Email address ${this.state.email} already in use.`);
          break;
        case 'auth/invalid-email':
          console.log(`Email address ${this.state.email} is invalid.`);
          break;
        case 'auth/operation-not-allowed':
          console.log(`Error during sign up.`);
          break;
        case 'auth/weak-password':
          console.log('Password is not strong enough. Add additional characters including special characters and numbers.');
          break;
        default:
          console.log(error.message);
          break;
      }
  });

希望那能有所帮助!


在 catch 语句块中进行检查是正确的,但是你在 switch 中漏掉了 break。 - Kid

22

在Firebase Admin SDK的情况下,有一个更简单的答案:

const uidExists = auth().getUser(uid).then(() => true).catch(() => false))
const emailExists = auth().getUserByEmail(email).then(() => true).catch(() => false))


3
请注意,以下内容仅适用于服务器端(管理 SDK),而不适用于客户端。 - Marc Van Daele

5
我这样使用fetchSignInMethodsForEmail
import { getAuth, fetchSignInMethodsForEmail } from 'firebase/auth';

const auth = getAuth();
let signInMethods = await fetchSignInMethodsForEmail(auth, email);
if (signInMethods.length > 0) {
  //user exists
} else {
   //user does not exist
}

请参考文档


1
这应该是被接受的答案。 - Pushkin
1
这应该是被接受的答案。 - undefined
我不确定这是否是一个理想的方式,因为它需要认证实例。楼主想要检查用户是否存在于已注销状态,我认为这个答案可能行不通。 - undefined
@rbtmr,兄弟,看看代码吧。它实际上是检查给定的电子邮件下是否存在用户。 - undefined
@DustinSpengler "或者在所有平台上使用fetchSignInMethodsForEmail客户端SDK方法。"https://github.com/firebase/firebase-js-sdk/issues/7644#issuecomment-1751301783与管理员无关。 - undefined
显示剩余5条评论

0
from firebase_admin import auth

user = auth.get_user_by_email(email)
print('Successfully fetched user data exists: {0}'.format(user.uid))

在 Python 中的管理员服务器

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接