我有一个google登录按钮,并存储在firebase.代码如下。
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if let error = error {
// ...
return
}
guard let authentication = user.authentication else { return }
let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,accessToken: authentication.accessToken)
Auth.auth().signIn(with: credential) { (authResult, error) in
if error == nil {
print("google signed in")
}
else
{
print(error?.localizedDescription)
}
}
}
它不应该允许用户通过google登录在firebase中,如果这样的用户没有在firebase数据库中创建,如何验证,然后提醒用户这种情况?
我认为要检查一个用户是否存在,你可以使用一个方法来检查。fetchSignInMethods
.
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if let error = error {
// ...
return
}
guard let authentication = user.authentication else { return }
guard let email = user.profile.email else { return }
Auth.auth().fetchSignInMethods(email: email) { (providers, error) in
if let error = error {
print(error)
return
}
if let providers = providers {
//This returns an array and will tell you if an user exists or not
//If the user exists you will get providers.count > 0 else 0
if providers.count > 0 {
//User Exists and you can print the providers like [google.com, facebook.com] <-- Providers used to sign in
} else {
//Show Alert user does not exist
}
}
}
}
因此,你只需要一个条件,即如果用户没有找到,你将呈现一个警报给用户,"用户没有在数据库中创建 "的权利!。
为此,你可以检查GoogleSignIn的错误代码,如:
guard let authentication = user.authentication else { return }
let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
accessToken: authentication.accessToken)
Auth.auth().signIn(with: credential) { (authResult, error) in
if let error = error {
if error._code == AuthErrorCode.userNotFound.rawValue {
//Present_your_desired_alert_here
}
}
}