How can I check if user exists in Firebase?

折月煮酒 提交于 2020-08-06 12:52:11

问题


I finally got my authentication to work in terms of creating users and logging in and out. But now, I want to implement something that checks if the user already exists in Firebase. I've looked it up but can't seem to find a concrete answer.

For example, if my email address is: abc12@gmail.com and someone else tries to signup with the same email address, how do I tell them it's already taken?

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

回答1:


The error that is returned from method createUserWithEmailAndPassword has a code property. Per the documentation the error code auth/email-already-in-use:

Thrown if there already exists an account with the given email address.

At very minimum you can utilize conditional statements such as if/else or switch to check for that code and display/log/dispatch/etc a message or code to the user:

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

Hopefully that helps!




回答2:


Simpler answer:

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


来源:https://stackoverflow.com/questions/51562995/how-can-i-check-if-user-exists-in-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!