如何在电话身份验证期间检查用户是否已存在于 firebase 中

Chr*_*iam 6 java android firebase firebase-authentication

我正在尝试创建一个仅使用来自 firebase 的电话授权的应用程序。由于登录/注册是通过相同的过程完成的,即验证发送的代码。如何检查用户是否已存在于 firebase 中?我需要这个来向他们展示合适的用户界面。

boj*_*eil 7

目前,唯一的方法是通过 Firebase Admin SDK。有一个 API 可以通过电话号码查找用户

admin.auth().getUserByPhoneNumber(phoneNumber)
  .then(function(userRecord) {
    // User found.
  })
  .catch(function(error) {
    console.log("Error fetching user data:", error);
  });
Run Code Online (Sandbox Code Playgroud)


Eln*_*ech 6

您可以通过比较它的元数据来检查用户是否已经存在于 Firebase 中。见代码示例:

PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.getCredential(verificationId, smsCode);
            FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential).addOnCompleteListener(PhoneLoginEnterCodeActivity.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
                        FirebaseUser user = task.getResult().getUser();
                        long creationTimestamp = user.getMetadata().getCreationTimestamp();
                        long lastSignInTimestamp = user.getMetadata().getLastSignInTimestamp();
                        if (creationTimestamp == lastSignInTimestamp) {
                            //do create new user
                        } else {
                           //user is exists, just do login
                        }
                    } else {
                        // Sign in failed, display a message and update the UI
                        if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                            // The verification code entered was invalid
                        }
                    }
                }
            });
Run Code Online (Sandbox Code Playgroud)