【问题标题】:How can I check if the phone number already exists in the Firebase Authentication? [duplicate]如何检查电话号码是否已存在于 Firebase 身份验证中? [复制]
【发布时间】:2019-03-11 14:56:55
【问题描述】:

我在我的 Android 应用程序中使用了带有电话号码的 Firebase 身份验证。但是firebase并没有像电子邮件密码认证那样为登录和注册提供不同的功能。如何检查用户是否已经存在?

【问题讨论】:

  • 在注册过程中,如果电话号码存在,您将收到错误消息,如果您登录成功则登录,则用户存在。你能用代码详细说明你的问题吗

标签: android firebase firebase-authentication


【解决方案1】:

在这种情况下,您可以做的是将每个注册用户的电话号码存储在 Firebase 数据库的 phone 节点中。

然后,当使用电话号码为新用户签名时,您可以在电话节点中运行检查电话号码是否存在。

要将电话号码存储在数据库中名为 phone 的节点中,您可以使用如下代码:

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();
                }
            }
        });
    }

在上面的代码中,phoneNumber 是您要注册的用户号。我也使用了相同的标题名称和值,即phoneNumber 本身。您可以使用名称或任何其他名称。

现在,当您注册一个新用户时,您应该使用以下代码在您的数据库中的 phone 节点中运行检查。您可以在上面的代码中为这个新方法添加实例。

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

                    }
                });

}                

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-09
    • 1970-01-01
    • 2020-09-05
    • 2020-08-18
    • 1970-01-01
    • 2019-02-22
    • 2020-01-28
    • 1970-01-01
    相关资源
    最近更新 更多