How can I check if the phone number already exists in the Firebase Authentication? [duplicate]

[亡魂溺海] 提交于 2020-08-10 03:57:05

问题


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?


回答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:

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) {

                    }
                });

}                


来源:https://stackoverflow.com/questions/52676825/how-can-i-check-if-the-phone-number-already-exists-in-the-firebase-authenticatio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!