首页 > 解决方案 > Firebase - 如何在创建新用户之前检查电话身份验证中是否存在电话号码

问题描述

在登录新用户或创建新用户时使用电子邮件有 2 种不同的方法签名。在创建新用户时,如果电子邮件已存在,则会返回错误;如果电子邮件不存在,则将用户登录,则会返回错误:

// create account
Auth.auth().createUser(withEmail: emailTextField.text!, password: passwordTextField.text!, completion: { (authDataResult, error)

    if let error = error {

       // if this email address already exists an error will be returned
       return
    }
})

// login 
Auth.auth().signIn(withEmail: emailTextField.text!, password: self.passwordTextField.text!, completion: { (authDataResult, error) in

    if let error = error {

       // if this email address isn't inside the system then an error will be returned
       return
    }
})

但是,当使用用户的电话号码记录他们或创建一个新帐户时,我必须对这两种情况使用相同的方法签名。

func loginExistingUserOrCreateNewOne(phoneNumber: String, verificationCode: String) {

    PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber, uiDelegate: nil) { (verificationID, error) in

        if let error = error { return }

        guard let verificationId = verificationID else { return }

        let credential = PhoneAuthProvider.provider().credential(withVerificationID: verificationId, verificationCode: verificationCode)

        Auth.auth().signIn(with: credential, completion: { (authDataResult, error) in

            guard let authUser = authDataResult else { return }

            let checkUsersRef = Database.database().reference().child("users").child(authUser.user.uid)
            checkExistingUsersRef.observeSingleEvent(of: .value, with: { (snapshot) in

                if !snapshot.exists() {
                    // this is a new user, now add them to the users ref

                    let newUserDict = ["signupDate": Date().timeIntervalSince1970]
                    checkUsersRef.updateChildValues(newUserDict, withCompletionBlock: { (error, ref) in

                        if let error = error {

                            // because there is an error this ref was never updated so now I have to sign this user out and they have to start over agin
                            do {
                                try Auth.auth().signOut()

                            } catch let err as NSError {

                                // alert user there is a major problem
                            }
                            return
                        }

                        // if no error let them go to HomeVC
                    })

                    return
                }

                // this is a previous user fetch dict data and let them proceed to HomeVC
                guard let previousUserDict = snapshot.value as? [String: Any] else { return }

                // get newUserDict values and let them go to HomeVC
            })
        })
    }
}

如果用户已经有一个帐户,我需要从用户 ref 获取一些数据,然后让他们继续使用 HomeVC。如果用户之前从未注册过,那么我必须将它们添加到用户引用中,然后让他们继续。这是一个两步的过程。

问题是这些额外的步骤似乎是不必要的。例如,使用电子邮件签名或登录会返回错误,因此无需在另一个 ref 中创建和检查该电子邮件是否已存在。

除了在上面的代码中使用该过程之外,还有其他方法可以确定电话号码在创建新帐户之前是否存在,或者在登录时是否不存在?

标签: iosswiftfirebasefirebase-realtime-databasefirebase-authentication

解决方案


您将需要使用 admin sdk通过电话号码查找用户

admin.auth().getUserByPhoneNumber(phoneNumber)
  .then(function(userRecord) {
    // User exists.
  })
  .catch(function(error) {
    if (error.code === 'auth/user-not-found') {
      // User not found.
    }
  });

您可以使用云函数来托管 HTTP 端点。只有通过运行服务器端的经过身份验证的 API(使用 Firebase Admin SDK)才能通过电话号码查找用户。


推荐阅读