【问题标题】:How can I check if user exists in Firebase?如何检查用户是否存在于 Firebase 中?
【发布时间】:2019-01-04 21:01: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);
    });
}

【问题讨论】:

标签: javascript reactjs firebase firebase-authentication


【解决方案1】:

从方法createUserWithEmailAndPassword 返回的错误具有code 属性。根据documentation 错误code auth/email-already-in-use:

如果已经存在使用给定电子邮件的帐户,则抛出 地址。

您至少可以利用if/else 或switch 等条件语句来检查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。
【解决方案2】:

更简单的答案:

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

【讨论】:

    【解决方案3】:
    from firebase_admin import auth
    
    user = auth.get_user_by_email(email)
    print('Successfully fetched user data exists: {0}'.format(user.uid))
    

    在 python 管理服务器中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-17
      • 2017-01-28
      • 2018-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-26
      • 1970-01-01
      相关资源
      最近更新 更多