I have used the firebase authentication with phone number in my android app. But firebase doesn't give different functions for sign in and sign up like the email password authentication. How can I check if the user already exists?
-
1During sign up you will get an error if phone number exists, in case of login if your login is success then user exists. Can you elaborate your problem with codes – Rahul Singh Chandrabhan Oct 06 '18 at 07:50
1 Answers
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:
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential){
mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@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 database
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("phone");
ref.child(phoneNumber).setValue(phoneNumber);
}
else if(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.
boolean checkForPhoneNumber(String number){
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.orderByChild("phone").equalTo(number).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
return true;
else
return false;
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}

- 2,372
- 2
- 12
- 20