25

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: [email protected] 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);
    });
}
2

4 Answers 4

39

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Checking inside a catch is correct, but you are missing break in the switch.
25

There's a simpler answer in the case of firebase admin sdk:

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

2 Comments

note that these only work server side (admin SDK), not client side.
This could be improved by checking for err.code === "auth/user-not-found". getUser could fail for other reasons.
11

I use fetchSignInMethodsForEmail like this:

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
}

Docs for reference

Update Sept 15 2023: Firebase now disables this feature by default to avoid Email Enumerarion. According to Google:

Email enumeration is a type of brute-force attack in which a malicious actor attempts to guess or confirm users in a system by passing an email address to the API and checking the response.

You can still use this feature by enabling it in your Firebase console by navigating to Authentication -> Settings -> User Actions and then disabling email enumeration protection: enter image description here

Make sure to read about the risk of disabling this on your platform

7 Comments

I don't know if this is a ideal way as it requires auth isntance. the OP is wanting to check if user exists in logged out state in which I don't think this answer would work
@rbtmr Thats not true. The question states "I want to implement something that checks if the user already exists in Firebase". Thanks for the downvote broski.
@DustinSpengler "For example, if my email address is: [email protected] and someone else tries to signup with the same email address, how do I tell them it's already taken?"
@DustinSpengler no it doesnt. i ran into the same issue last month, cloud.google.com/identity-platform/docs/admin/…
"A list of sign-in methods for a specified email address is no longer returned when calling the createAuthUri REST API or the fetchSignInMethodsForEmail client SDK method on all platforms."
|
0
from firebase_admin import auth

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

In python admin server

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.