How does Firebase Auth UI deal with reauthentication?

后端 未结 1 2043
长情又很酷
长情又很酷 2021-01-13 17:58

I\'m using Firebase Auth for my Swift iOS app. Google recommends using Firebase Auth UI as a \"drop in\" authentication system, but it only handles the initial login. I\'m n

相关标签:
1条回答
  • 2021-01-13 18:44

    Regarding the error code, the documentation just needs updating. The error code is now called FIRAuthErrorCode.errorCodeRequiresRecentLogin.

    Now, as of the UI problem you're facing, why not just present a UIAlertController with a text field that the users can use to enter their passwords for re-authentication? It's certainly much simpler (and user-friendlier) than creating an entire view controller.

    Here's a pretty straightforward sample of how you can re-authenticate your users without going through so much trouble:

    // initialize the UIAlertController for password confirmation
    let alert = UIAlertController(title: "", message: "Please, enter your password:", preferredStyle: UIAlertControllerStyle.alert)
    // add text field to the alert controller
    alert.addTextField(configurationHandler: { (textField) in
        textField.placeholder = "Password"
        textField.autocapitalizationType = .none
        textField.autocorrectionType = .no
        textField.isSecureTextEntry = true
    })
    // delete button action
    alert.addAction(UIAlertAction(title: "Delete account", style: UIAlertActionStyle.destructive, handler: {action in
        // retrieve textfield
        let txtFld = alert.textFields![0]
        // init the credentials (assuming you're using email/password authentication
        let credential = FIREmailPasswordAuthProvider.credential(withEmail: (FIRAuth.auth()?.currentUser?.email)!, password: txtFld.text!)
        FIRAuth.auth()?.currentUser?.reauthenticate(with: credential, completion: { (error) in
            if error != nil {
                // handle error - incorrect password entered is a possibility
                return
            }
    
            // reauthentication succeeded!
        })
    }))
    // cancel reauthentication
    alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: {action in }))
    
    // finally, present the alert controller
    self.present(alert, animated: true, completion: nil)
    

    Whenever you need to change the user's email or delete their account (password reset doesn't require a login at all), use the snippet above to just pop up an alert controller where they can re-enter their password.

    EDIT: Please note that the code provided above force-unwraps the current user's email, so make sure you have a user logged-in at that stage or your app will crash.

    0 讨论(0)
提交回复
热议问题