18

I am using firebase phone Authentication . When a user creates a account using phone number and next time he creates account with same phone number Than I want to show a message saying account already exists

8 Answers 8

14

In order to detect whether that phone number has already been used for account registration, you can't only rely on the default authentication table. But also has to use the Firebase database to create a Dummy user table for checking.

For example, you can create a json tree to save user data in the realtime database in to something structured like this:

enter image description here

And your piece of code should looks similar to:

On the piece of code of successful login/user registration:

DatabaseRef userRef = FirebaseDatabase.getInstance.getRef("users");
userRef.orderByChild("telNum").equalTo(phoneNumber).addListenerForSingleValueEvent(new ValueEventListener() {

     if (dataSnapshot.getValue() != null){
        //it means user already registered
        //Add code to show your prompt
        showPrompt();
     }else{
        //It is new users
        //write an entry to your user table
        //writeUserEntryToDB();
     }
}
3

I have done this into my project and it is working perfectly, you can use this, you can use your phone number instead of "deviceId".

 mFirebaseDatabaseRefrence.orderByChild("deviceId").equalTo(deviceId).addListenerForSingleValueEvent(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.getValue() != null) {
                    Log.d(TAG, "Datasnap Shots: " + dataSnapshot.getValue());
                      /* if alredy exist and check for first time, second time isExist=true*/
                    if (!isExist) {

                        for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
                            UserbasicInfo user = userSnapshot.getValue(UserbasicInfo.class);
                              Toast.makeText(UserInfoActivity.this, "User already exist...!", Toast.LENGTH_SHORT).show();

                        }

                    }
                    isExist = true;
                } else {
                    isExist = false;
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        /*if not exist add data to firebase*/
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "isExist: " + isExist);
                if (!isExist) {
                    addDataToDB(false);
                } else {
                    addDataToDB(true);

                }
            }
        };
        new Handler().postDelayed(runnable, 5000);
3

onTask result check FirebaseAuthUserCollisionException

if (task.getException() instanceof FirebaseAuthUserCollisionException) {
    Toast.makeText(Signup.this, "User already exist.",  Toast.LENGTH_SHORT).show();
}
3
2

For the solution,

After signup please make some entry in Database which makes an identity of the user, so next time you can identify user already signup.

After OTP verification check in RealTime database already Mobile number exists then so its already otherwise do an entry of that particular mobile number.

1
DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("Users");
userRef
    .orderByChild("phonenumber")
    .equalTo(mMobile.getText().toString())
    .addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.getValue() != null) {
                //it means user already registered
                //Add code to show your prompt
                OpenErrorAlrt("Mobile Number already registed");
            } else {
                Intent intent = new Intent(getApplicationContext(), OTPVerifyActivity.class);
                intent.putExtra("phonenumber", mMobile.getText().toString());
                startActivity(intent);
            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
0

I have handled this way. Firebase throws some exception on having some error while authentication and other invalid things we just have to handle them and notify the user.

sample code:

    private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "signInWithCredential:success");
                        //do something on success
                    } else {
                        //handle the error here
                        showInfoToUser(task)
                        }
                    }
                }
            });
}

and check what kind of error we are getting by checking exceptions here

 private void showInfoToUser(Task<AuthResult> task) {
    //here manage the exceptions and show relevant information to user
    hideProgressDialog();
    if (task.getException() instanceof FirebaseAuthUserCollisionException) {
        showSnackBar(getString(R.string.user_already_exist_msg));
    } else if (task.getException() instanceof FirebaseAuthWeakPasswordException) {
        showSnackBar(task.getException().getMessage());
    } else if (task.getException() instanceOf FirebaseAuthInvalidCredentialsException){
        //invalid phone /otp
        showSnackBar(task.getException().getMessage());
    }
    else {
        showSnackBar(getString(R.string.error_common));
    }
}
0

This is very easy way to check whether a user is already register with firebase.

 AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = mAuth.getCurrentUser();
                        if(task.getResult().getAdditionalUserInfo().isNewUser()){
                            register(user);
                        }else{
                            Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                            startActivity(intent);
                        }
                        Toast.makeText(LoginActivity.this, "welcome"+user.getDisplayName(), Toast.LENGTH_SHORT).show();
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Toast.makeText(LoginActivity.this, "signin Failed", Toast.LENGTH_SHORT).show();
                    }

                    // ...
                }
            });
0

It's pretty simple if you are using have Firebase Admin SDK.

I'm using it with Node.js and it looks something like this.

const admin = require("firebase-admin");
const auth = admin.auth();

app.use("/check", (req, res, next) => {
   auth
    .getUserByPhoneNumber(phone)
    .then((res) => {
      res.status(406).json({ message: "USER ALREADY HAVE THIS PHONE" });
    })
    .catch((err) => {
      res.status("200").json({ message: "OK" });
    });
});

In Flutter then we can send a GET/POST request to our Node.js server and collect the response.

(For those who don't know about admin sdk, it is a server side sdk used with firebase for some useful operations like reset any user's password etc.)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.