How to check if email exists in firebase Auth

Viewed 3678

I have a two-step Login form where the user enters their email first, then is taken to the next page where they enter their password. Prior to taking the user to the password page, I want to check if the email entered by the user is valid and whether it exists in firebase. I have read a few posts about using fetchSignInMethodsForEmail. However, I'm not quite sure how to implement this.

The idea is if the email does exist the user is taken to the password page, however, if the email does not exist a snackbar pops up with a button taking the user to the register page. How would I go about doing this?

This is what I have so far...

FirebaseAuth auth = FirebaseAuth.instance;


    final nextButton = Container(
      margin: const EdgeInsets.only(
        top: 30.0,
      ),
      child: FloatingActionButton(
        onPressed: () async {
          try {
            List<String> userSignInMethods = await auth.fetchSignInMethodsForEmail(email)(
               email: _emailController.text,
            );
            if (userSignInMethods != null) {
              final page = LoginPassword();
              Navigator.of(context).push(CustomPageRoute(page));
            }
          } catch (e) {
            print(e);
            //TODO: Snackbar 
          }
        },
        tooltip: 'Next',
        backgroundColor: AppTheme.define().primaryColor,
        child: Icon(
          AppIcons.next_button,
          size: 20.0,
        ),
      ),
    );

The fetchSignInMethodsForEmail isn't implemented properly, I'm getting an error.

3 Answers

This probably isn't what you are looking for but what I usually do is store the users in a collection in firestore since that allows me to store multiple values for the user like nickname, picture, points etc. If you want some sample code on how to do this, let me know

EDIT

This is some code to help you get started.

First set up the firestore and set up a collection named users. Create a document in it with your mail id and add the fields you want for a user in it. If you do not do this you will get an error that the collection cannot be found or firestore is not set up

While signing up, do something like this given the email is in variable email and password in pass

FirebaseFirestore.instance.collection('users').doc(email).set((){
   "email":email,
   "pass":pass,
   "nick":nick,//You can add more fields or remove them
});

When you want to check if the email exists, do something like

QuerySnapshot query = await FirebaseFirestore.instance.collection('users').where('email',isEqualTo:email).get();
if (query.docs.length==0){
   //Go to the sign up screen
}
else {
   //Go to the login screen
}

Now to check the password while signing in, do something like

QuerySnapshot query = await FirebaseFirestore.instance.collection('users').where('email',isEqualTo:email).get();//You can also pass this query as a parameter when you push the login screen to save some time
if (query.docs[0].get('pass')==pass){
   //Go ahead login
}
else{
   //Display an error message that password is wrong
}

If you want to store the data to automatically login when the user opens the app next time, look into the Shared Preference library.

If you want to pass the user data around, create a class called User()


class User {
  String email;
  String pass;
  String nick;

  User(this.email,this.nick,this.pass);
}

Then you can pass it around and easily manage the user data

For the method fetchSignInMethodsForEmail looking at the documentation, An empty List is returned if the user could not be found. It can't be null since that method returning an empty list, so you can check for the length. userSignInMethods.length > 0

You can try catch and exception like as my code. And let me know.

try {
  _firbaseAuth.createUserWithEmailAndPassword(
    email: 'ab@gmail.com', 
    password: '123456'
  );
} catch(signUpError) {
  if(signUpError is PlatformException) {
    if(signUpError.code == 'ERROR_EMAIL_ALREADY_IN_USE') {
      /// ab@gmail.com has alread been registered.
    }
  }
}
Related