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

wgx48brx  于 2023-02-13  发布在  其他
关注(0)|答案(4)|浏览(152)

我终于让我的认证在创建用户和登录退出方面起作用了。但是现在,我想实现一些东西来检查用户是否已经存在于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);
    });
}
ygya80vv

ygya80vv1#

方法createUserWithEmailAndPassword返回的错误具有code属性。根据文档,错误codeauth/email-already-in-use
如果已存在具有给定电子邮件地址的帐户,则抛出。
您至少可以使用if/elseswitch等条件语句来检查code,并向用户显示/log/dispatch/etc消息或代码:

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

希望能有所帮助!

aor9mmx1

aor9mmx12#

对于firebase admin sdk,有一个更简单的答案:

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

qhhrdooz3#

我是这样使用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
}

参考文件

rsaldnfx

rsaldnfx4#

from firebase_admin import auth

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

在python管理服务器中

相关问题