简体   繁体   中英

Firebase Auth - with Email and Password - Check user already registered

I want to check when a user attempts to signup with createUserWithEmailAndPassword() in Firebase user Authentication method, this user is already registered with my app.

注册用户

To detect whether a user with that email address already exists, you can detect when the call to createUserWithEmailAndPassword () fails with auth/email-already-in-use . I see that @Srinivasan just posted an answer for this.

Alternatively, you can detect that an email address is already used by calling fetchSignInMethodsForEmail() . The usual flow for this is that you first ask the user to enter their email address, then call fetchSignInMethodsForEmail , and then move them to a screen that either asks for the rest of their registration details (if they're new), or show them the provider(s) with which they're signed up already.

When the user trying to create an user with same email address, the task response will be "Response: The email address is already in use by another account."

mFirebaseAuth.createUserWithEmailAndPassword(email,password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {                           
                        if(task.isSuccessful()){
                           //User registered successfully
                        }else{
                            Log.i("Response","Failed to create user:"+task.getException().getMessage());
                        }
                    }
                });

Firebase 身份验证登录方法 高级设置

First of all, you need to make sure you have that restriction enabled in Firebase console (Account and email address settings). Take a look at @Srinivasan's answer.

Then, do this in your java code:

firebaseAuthenticator.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (!task.isSuccessful()) {

                            if (task.getException() instanceof FirebaseAuthUserCollisionException) {
                                Toast.makeText(SignUpActivity.this, "User with this email already exist.", Toast.LENGTH_SHORT).show();
                            }


                        } else {
                            sendVerificationEmail();
                            startActivity(new Intent(SignUpActivity.this, DetailsCaptureActivity.class));
                        }

                        // ...
                    }
                });

This is where the trick happens:

if (task.getException() instanceof FirebaseAuthUserCollisionException) {
                            Toast.makeText(SignUpActivity.this, 
          "User with this email already exist.", Toast.LENGTH_SHORT).show();

Several exceptions can be thrown when registering a user with email and password, but the one we are interested in is the FirebaseAuthUserCollisionException . As the name implies, this exception is thrown if the email already exists. If the exception thrown is an instance of this class, let the user know.

As a practice of @Frank's answer here is the code of using fetchProvidersForEmail()

private boolean checkAccountEmailExistInFirebase(String email) {
                FirebaseAuth mAuth = FirebaseAuth.getInstance();
                final boolean[] b = new boolean[1];
                mAuth.fetchProvidersForEmail(email).addOnCompleteListener(new OnCompleteListener<ProviderQueryResult>() {
                    @Override
                    public void onComplete(@NonNull Task<ProviderQueryResult> task) {
                        b[0] = !task.getResult().getProviders().isEmpty();
                    }
                });
                return b[0];
            }

I was looking into this kind of condition where we can detect if user exists or not and perform registration and login. fetchProvidersForEmail is best option right now. I have found this tutorial. Hope it helps you too!

See : Manage Users

UserRecord userRecord = FirebaseAuth.getInstance().getUserByEmail(email);
System.out.println("Successfully fetched user data: " + userRecord.getEmail());

This method returns a UserRecord object for the user corresponding to the email provided.

If the provided email does not belong to an existing user or the user cannot be fetched for any other reason, the Admin SDK throws an error. For a full list of error codes, including descriptions and resolution steps, see Admin Authentication API Errors .

private ProgressDialog progressDialog;
progressDialog.setMessage("Registering, please Wait...");
progressDialog.show();

mAuth.createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                    //checking if success
                    if (task.isSuccessful()) {
                        //Registration was successfull:
                        Toast.makeText(RegistrationActivity.this, "Successfully registered!", Toast.LENGTH_LONG).show();

                    } else {
                        //Registration failed:
                        //task.getException().getMessage() makes the magic
                        Toast.makeText(RegistrationActivity.this, "Registration failed! " + "\n" + task.getException().getMessage(), Toast.LENGTH_LONG).show();
                    }
                    progressDialog.dismiss();
                }
            });

Add below code to MainActivity.java file.When user attempt to register with the same email address a message "The email address is already used by another account" will pop up as a Toast

mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                    if(!task.isSuccessful()){

                        Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();

                    }
                    if(task.isSuccessful()){
                        Toast.makeText(MainActivity.this, "Sign up successfull", Toast.LENGTH_SHORT).show();
                    }

                }
            });

You do not have to do anything because the backend of Firebase will do the job.

Unless you are referring to reauthenticating of the app. Take a scenario for an example, w

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM