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

新手上路,请多包涵

我终于让我的身份验证在创建用户和登录和注销方面起作用。但是现在,我想实现一些检查用户是否已经存在于 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);
    });
}

原文由 sp92 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 492
2 个回答

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

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

At very minimum you can utilize conditional statements such as if / else or switch to check for that code and display/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;
      }
  });

希望这有帮助!

原文由 Alexander Staroselsky 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

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

原文由 Arutyun Enfendzhyan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题