如何使用Flutter检查电话号码是否已在Firebase身份验证中注册

时间:2020-05-19 03:35:25

标签: firebase flutter firebase-authentication

所以我正在使用Firebase的电话身份验证的flutter应用程序中进行简单的注册和登录屏幕。对于注册,无法注册新用户,因为该用户提供了他的电话号码并获得了OTP。但是登录时,我想检查输入的号码是否已经注册。如果是这样,他将获得otp并登录,或者如果尚未注册,则要求先注册。

2 个答案:

答案 0 :(得分:1)

Firebase管理员SDK支持此功能。以下是设置Firebase管理员(documentation)的方法。设置好管理员后,您可以使用cloud_functions程序包从firebase admin SDK调用API,而我们将使用的API允许我们通过电话号码(documentation)获取用户。如果API响应是用户记录,则表明存在电话。

在此示例中,我使用的是node.js。在functions / index.js中:

H

在您的飞镖代码中:

exports.checkIfPhoneExists = functions.https.onCall((data, context) => {
   const phone = data.phone
   return admin.auth().getUserByPhoneNumber(phone)
    .then(function(userRecord){
        return true;
    })
    .catch(function(error) {
        return false;
    });
});

答案 1 :(得分:1)

一旦OTP发送给用户,您可以在验证OTP功能中验证该用户是新用户还是现有用户

verifyOtp(String input, context) async {
  String retVal = "error";
  OurUser _user = OurUser();
  print(input);
  final AuthCredential credential = PhoneAuthProvider.credential(
      verificationId: _verificationId, smsCode: input);
  try {
    //  await _auth.signInWithCredential(credential);
    UserCredential _authResult = await _auth.signInWithCredential(credential);

    // Here i have to save the details of the user in the database
    if (_authResult.additionalUserInfo.isNewUser) {
      currentUser.uid = _authResult.user.uid;
      currentUser.phone = _inputText;
      currentUser.type = "Customer";

      retVal = await OurDatabase().createUser(currentUser);
    } else {
      // get the information of the user from the database this already exists
      currentUser = await OurDatabase().getUserInfo(_authResult.user.uid);
      if(currentUser!= null) {
        Navigator.pushNamedAndRemoveUntil(
            context, "/homescreen", (route) => false);
      }
    }
    print("End of the await");

    // when signup with the otp
    if (retVal == "success") {
      print("why not inside this mane");
      Navigator.pushNamedAndRemoveUntil(
          context, "/homescreen", (route) => false);
    }

    saveAllData();
  } catch (e) {
    print(e);
    print("Something went wrong");
    //prin
  }
}

现在这是您想要验证用户的 OTP 并且在验证顶部之后您可以知道该用户确实是新用户还是旧用户的时候,但是如果您想事先知道那是最好的解决方案将是在 Firestore 中创建一个新集合,该集合只有一个文档(因此您只需为读取一个文档付费),其中仅包含在您的应用程序中注册的所有用户数量,