Pregunta

I am using firebase (with Angularfire) for an html5 phone app. The user inputs only their email in the start screen, and then, depending on whether that email is already registered or not, the user is redirected to the login or registration page, respectively. For step1, how can we query the firebase simple login to determine if the email is registered or not?

¿Fue útil?

Solución

Update 7/19/2018

The previous mention method is deprecated. Now fetchSignInMethodsForEmail is used.

Update 6/26/2016

A lot has changed since this was originally posted, Firebase Authentication is no longer called Firebase Simple Login.

Additionally, it looks like a new method is available fetchProvidersForEmail which might provide a solution to this problem.

From the docs:

fetchProvidersForEmail(email) returns firebase.Promise containing non-null Array of string

Gets the list of provider IDs that can be used to sign in for the given email address. Useful for an "identifier-first" sign-in flow.

I have not tested this but I'd imagine if you call that method and receive an array of providers then the e-mail must already be registered with one or more authentication providers.

Old Answer

I don't believe you can query the Firebase Simple Login directly for that information without either trying to actually login the user or register them.

What you'd need to do is store a list of registered e-mails during your registration process and query that list instead. Then you can query that path and if it comes back with data, it exists, otherwise it doesn't.

Otros consejos

Well Following #Kato's and #MikePugh's commented suggestions I am gonna write this solution and it worked for me.

Solutio#1 (highly recommended)

 mAuth.fetchProvidersForEmail("emailaddress@gmail.com").addOnCompleteListener(new OnCompleteListener<ProviderQueryResult>() {
        @Override
        public void onComplete(@NonNull Task<ProviderQueryResult> task) {
            if(task.isSuccessful()){
          ///////// getProviders().size() will return size 1. if email ID is available. 
                task.getResult().getProviders().size();
            }
        }
    });

Solution#2

Create a dummy FirebaseUser object.

FirebaseUser firebaseUser = null;
private FirebaseAuth mAuth;

private void isEmailAlreadyUsed() {
    mAuth = FirebaseAuth.getInstance();

///// here I am gonna create dummy user at **Firebase** with the Entered email Id (Email to check against) 

    mAuth.createUserWithEmailAndPassword(mEmailView.getText().toString(), "dummypass")
            .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d(TAG, "createUser:onComplete:" + task.isSuccessful());


                    if (task.isSuccessful()) {
                        /////user do not exit so good to initialize firebase user.              
                    firebaseUser = task.getResult().getUser();
                    } else {
                        if(task.getException().getMessage().equals("The email address is already in use by another account.")) {
                          Log.d(TAG, "This email ID already used by someone else");     
                        }
                    }
                }
            });
}

Later on when user enter password and press SIGNUP button then you can just update password of the user which was set as dummypass.

   boolean isSignUpMade = false;
    if (firebaseUser != null)
        firebaseUser.updatePassword(password)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        signUpCallProgress.setVisibility(View.VISIBLE);
                        if (task.isSuccessful()) {
                            isSignUpMade = true;
                            Log.d(TAG, "User password updated.");
                        } else {
                            isSignUpMade = false;
                            Log.d(TAG, "User password not updated.");
                        }
                    }
                });

You can see I have used isSingUpMade variable just to insure that user presses SINGUP button.

If user wants to leave without signing up than that dummy user must be deleted from FIREBASE server.

so here is the logic.

 @Override
public void onBackPressed() {
    if (!isSignUpMade) {
        if (firebaseUser != null)
            firebaseUser.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "User account deleted.");
                    }
                }
            });
    }
    super.onBackPressed();
}

A little easier example to understand how to catch if the user already exists when signing up with email / password

  1. Catch the error
  2. If "auth/email-already-in-use" exist
  3. Call another function that contains .signInWithEmailAndPassword()

Example

    .createUserWithEmailAndPassword(email, password)

    .catch(error => {
      // Handle Errors here.
      const errorCode = error.code;
      const errorMessage = error.message;

      // Catch this errorCode to know if user exists
      if (errorCode === 'auth/email-already-in-use') {
        // Call function X to sign user in instead
        signInMail(email, password);
        return;
      } 

      // Weak password?
      else if (errorCode == 'auth/weak-password') {
        console.log('The password is too weak.');
      } 

     else {
        console.log(errorMessage);
      }
      console.log(error);
    })

Important part that you want to use in your own code would be this

.catch(error => {
      // Handle Errors here.
      const errorCode = error.code;
      const errorMessage = error.message;
      if (errorCode === 'auth/email-already-in-use') {
        console.log('This email is already in use');
        // Your action
        return;
      }
    })

You can add following codes before register()_method in your registerActivity.

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(email.equals(user.getEmail().trim())) {
    Toast.makeText(this, "Email is taken", Toast.LENGTH_SHORT).show();
    return;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top