How Can I Check If The Phone Number Already Exists In The Firebase Authentication?
Solution 1:
What you can do in this case is that, store the phone number of every signed up user in the phone
node of your Firebase database.
Then when signing a new user from a phone number, you can run a check in your phone node, that wether the phone number exists or not.
To store the phone number in a node named phone
in your database, you can use a code like this:
privatevoidsignInWithPhoneAuthCredential(PhoneAuthCredential credential){
mAuth.signInWithCredential(credential).addOnCompleteListener(this, newOnCompleteListener<AuthResult>() {
@OverridepublicvoidonComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
// you may be using a signIn with phone number like this, now here you can save the phone number in your databaseDatabaseReferenceref= FirebaseDatabase.getInstance().getReference().child("phone");
ref.child(phoneNumber).setValue(phoneNumber);
}
elseif(task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(MainActivity.this, "OTP is incorrect", Toast.LENGTH_SHORT).show();
}
}
});
}
In the above code, phoneNumber
is the number of the user you're signing up. Also I have used the heading name and value same, and that is, phoneNumber
itself. You can use a name or anything else, you want.
Now when you're signing up a new user, you should run a check in your phone
node in your database, using the following piece of code. You can add instance to this new method in the code above.
booleancheckForPhoneNumber(String number){
DatabaseReferenceref= FirebaseDatabase.getInstance().getReference();
ref.orderByChild("phone").equalTo(number).addListenerForSingleValueEvent(newValueEventListener() {
@OverridepublicvoidonDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
returntrue;
elsereturnfalse;
}
@OverridepublicvoidonCancelled(@NonNull DatabaseError databaseError) {
}
});
}
Post a Comment for "How Can I Check If The Phone Number Already Exists In The Firebase Authentication?"