Home > Software engineering >  how I can check if the email is already exist in authentication firebase
how I can check if the email is already exist in authentication firebase

Time:11-16

I have this function to create authentication in my firebase but the problem is when the user enters an email that already exists my app will stop com.google.firebase.auth.FirebaseAuthUserCollisionException: The email address is already in use by another account.
how I can check if the email is already exists in the authentication

fun createUserWithEmailAndPassword(email: String, password: String) {
    viewModelScope.launch(Dispatchers.IO) {
        auth
            .createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    user.userID = auth.uid!!
                    Log.d("TAG", "${auth.uid}")
                    addUser(user)
                } else {
                    Log.d("userVM" ,task.result.toString())
                }
            }
    }
}

CodePudding user response:

The FirebaseAuth#createUserWithEmailAndPassword(@NonNull email: String, @NonNull password: String) method:

Tries to create a new user account with the given email address and password. If successful, it also signs the user into the app.

This means that if you try to create a user that already exists, a FirebaseAuthUserCollisionException will be thrown:

Thrown when an operation on a FirebaseUser instance couldn't be completed due to a conflict with another existing user.

If a user already exists, you should call another method that only signs in the user which is called
signInWithEmailAndPassword(@NonNull email: String, @NonNull password: String):

Tries to sign in as a user with the given email address and password.

That doesn't try to create the user again. If you want to check if a user already exists, you should add user details in Firestore for example, and use my solution from the following post:

  • Related