ios - 如何在 firebase 中管理用户的不同身份验证

标签 ios swift firebase swift3 firebase-authentication

请帮助我在以下情况下找到正确的解决方案。

我正在使用 swift 开发 ios 应用程序,它将使用 Firebase 作为后端。

用户应该能够使用电子邮件/密码或/和使用 facebook 登录 firebase。也许以后会加上google。

对我来说,为每个真实用户拥有一个 firebase 帐户很重要,因为用户将获得奖励积分,如果在一个设备上(使用电子邮件登录)他将获得 X 积分而在其他设备上(使用facebook)他会有不同的观点。

这是我用来通过电子邮件登录的代码:

  //EMAIL REGISTER  
    @IBAction func registerAction(_ sender: Any) {

        if self.emailTextField.text == "" || self.passwordTextField.text == "" {

            Print( "Please enter email and password.")

        } else {

            FIRAuth.auth()?.createUser(withEmail: self.emailTextField.text!, password: self.passwordTextField.text!, completion: { (user, error) in

                if error == nil {
                    self.logoutButton.isHidden = false
                    self.usernameLabel.text = user!.email
                    self.emailTextField.text = ""
                    self.passwordTextField.text = ""
                } else {
                    Print("\((error?.localizedDescription)!)")
                }

            } )

        }
    }

    //EMAIL LOGIN
    @IBAction func loginAction(_ sender: Any) {

        if self.emailTextField.text == "" || self.passwordTextField.text == "" {
            print( "Please enter email and password.")
        } else {

            FIRAuth.auth()?.signIn(withEmail: self.emailTextField.text!, password: self.passwordTextField.text!, completion: { (user, error) in

                if error == nil {
                    self.logoutButton.isHidden = false
                    self.usernameLabel.text = user!.email
                    self.emailTextField.text = ""
                    self.passwordTextField.text = ""

                } else {

                    Print("\((error?.localizedDescription)!)")

                }
            })
        }
    }

这是我用来登录 facebook 的代码:

  func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {

        self.fbLoginButton.isHidden = true

        if error != nil {

            self.fbLoginButton.isHidden = false
            print(error.localizedDescription)
            return

        } else if (result.isCancelled) {

            print("canceled")
            self.fbLoginButton.isHidden = false

        } else {

            let credential = FIRFacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)

            FIRAuth.auth()?.signIn(with: credential) { (user, error) in
                if let error = error {
                    print(error.localizedDescription)
                    return
                }
            }
        }
    }

这两种方法都可以正常工作,但它们会创建两个单独的帐户。

它被设置为允许多个用户在设置中使用相同的电子邮件: enter image description here

我最终得到以下结果:

enter image description here

显然我希望这两个帐户自动合并。

Documentation描述了如何链接身份验证提供者的方式,但用户应该使用一种方法登录,只有在这之后才有可能链接帐户。 linkWithCredential 如果您已经拥有 oauth 凭证,则使用该方法。如果用户是在一台设备上使用电子邮件创建的,那么如果他决定在另一台设备上使用 facebook 再次登录,则该用户将无法正常工作。


使用这些方式中的任何一种登录后,FIRAuth.auth()?.addStateDidChangeListener 服务会显示我正在使用数据库的第二个 View Controller 。

覆盖函数 viewDidLoad() { super.viewDidLoad()

let user = FIRAuth.auth()?.currentUser
let dat = user?.providerData

let email = user?.providerData[0].email
let name = user?.displayName

if email != nil {
self.ref.child("user_profile").child("\(user!.uid)/email").setValue(email)
}

if name != {
self.ref.child("user_profile").child("\(user!.uid)/name").setValue(name)
}

假设我们使用 facebook 登录,也许可以找到具有相同电子邮件的用户的 UID 并运行更新?如果有很多用户,这不是一个好主意。

另一个想法是像这样使用电子邮件作为 id:

self.ref.child("user_profile").child("\(email)/name").setValue(name)

不确定这是否是一个好的选择?

感谢您的回复。

最佳答案

在没有匿名用户的第一台设备上使用他的电子邮件和密码登录后,如何从不同的设备登录用户。

创建用户后,您需要将电子邮件和密码保存到 NSUbiquitousKeyValueStore,这样其他设备就可以访问电子邮件和密码,因为您需要先登录用户,然后再关联他们的帐户到 Facebook,如下所示。

在 FB 控制台中
1. 帐户电子邮件地址设置:防止使用相同的电子邮件地址创建多个帐户这样,如果用户已经使用电子邮件地址登录,则不会再次创建帐户。

2.如果用户选择邮箱地址作为首次登录:

 var iCloudKeyStore: NSUbiquitousKeyValueStore = NSUbiquitousKeyValueStore()

FIRAuth.auth()?.createUser(withEmail: email, password: password) { (user, error) in

           // User created
            if error == nil{

                 // signed in successfully

                 //Save the password and the email. Or choose your way to save them
                 iCloudKeyStore.set(password, forKey: email)


            }else{

                //Erorr
            }
        }
  1. 现在用户在 Firebase 中有一个帐户,看起来像这样:

enter image description here 4. 现在在另一台设备上,用户决定使用 Facebook(不同的提供商)登录

在您使用 Facebook 登录用户并获得 fb 的 token 后:通常在 FBSDKAccessTokenDidChange 通知的函数监听器中,您使用 Firebase 使用 Facebook 的 token 登录用户。

let credential = FIRFacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)

    FIRAuth.auth()?.signIn(with: credential) { (user, error) in
        // ...
        if error != nil {
            // SETP 5. HERE

            let nsError = (error as! NSError)
            // Error: 17007 The email address is already in use by another account. ERROR_EMAIL_ALREADY_IN_USE

             if nsError.code == 17007{


                    print(error,user?.uid,nsError.code,"facebook user error")

                    let email = nsError.userInfo["FIRAuthErrorUserInfoEmailKey"] as? String
                    self.signInUserWithEmail(email: email!)
                    print("email",email)
                }


        }else{


            print(user!.uid,"facebook user login")
    }
  1. 由于用户已经使用此电子邮件地址拥有一个帐户,他现在正在尝试使用 Facebook 登录,因此会发生错误:如您在第 4 步中看到的,现在您需要先登录用户,然后再登录链接是 Facebook 帐户:

    func signInUserWithEmail(email:String){
    
        let password = iCloudKeyStore.string(forKey: email)
    
    
        FIRAuth.auth()?.signIn(withEmail: email, password: password, completion: { (user:FIRUser?, error:Error?) in
    
    
            if user != nil{
    
                self.linkAccountWihtFacebook()
                print(user?.uid)
    
            }else{
    
                print(error?.localizedDescription)
            }
        })
    
    }
    

    func linkAccountWihtFacebook(){

        let credential = FIRFacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
    
            FIRAuth.auth()?.currentUser?.link(with: credential, completion: { (user:FIRUser?, error:Error?) in
    
                if let LinkedUser = user{
    
                    print("NEW USER:",LinkedUser.uid)
    
                }
    
                if let error = error as? NSError{
    
                    //Indicates an attempt to link a provider of a type already linked to this account.
                    if error.code == FIRAuthErrorCode.errorCodeProviderAlreadyLinked.rawValue{
                        print("FIRAuthErrorCode.errorCodeProviderAlreadyLinked")
                    }
    
                    //This credential is already associated with a different user account.
                    if error.code == 17025{
    
                    }
    
                    print("MyError",error)
                }
    
            })
    }
    
  2. 这样您将在 Firebase 控制台中得到以下结果:

enter image description here

Firebase 文档: https://firebase.google.com/docs/auth/ios/account-linking

Link auth provider credentials to a user account

To link auth provider credentials to an existing user account:

1. Sign in the user using any authentication provider or method.

  1. Complete the sign-in flow for the new authentication provider up to, but not including, calling one of the FIRAuth.signInWith methods. For example, get the user's Google ID token, Facebook access token, or email and password.
  2. Get a FIRAuthCredential for the new authentication provider

关于ios - 如何在 firebase 中管理用户的不同身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41375219/

相关文章:

objective-c - 使用参数调用选择器

ios - 选择单元格时 UITableView 分隔符颜色发生变化

firebase - iOS 模拟器不支持此浏览器

javascript - 获取未捕获的类型错误 : . ..default 不是构造函数 - 来自 Vue 组件

ios - Firebase Unity Google-services-info.plist iOS无法正常运行

android - 寻找多平台分析解决方案?

ios - 使用新的位置数据更新核心数据(魔法记录)

ios - 我可以将 swiftdata 框架用于现有的 sqlite 数据库吗?

swift - 如何加载到弹出窗口中的不同 View ?

ios - 过滤唯一值以在消息收件箱中显示唯一用户名