如何在Firebase 3上更改密码时验证用户的当前密码?

时间:2016-07-16 11:11:58

标签: ios swift firebase firebase-authentication

我希望用户在更新密码时插入当前密码和新密码。

我搜索过Firebase文档,但没有找到验证用户当前密码的方法。

有人知道这是否可行?

3 个答案:

答案 0 :(得分:13)

在更改密码之前,您可以使用reauthenticate来实现它。

let user = FIRAuth.auth()?.currentUser
let credential = FIREmailPasswordAuthProvider.credentialWithEmail(email, password: currentPassword)    

user?.reauthenticateWithCredential(credential, completion: { (error) in
    if error != nil{
        self.displayAlertMessage("Error reauthenticating user")
    }else{
        //change to new password
    }
})

只需添加更多信息here,您就可以找到如何为您正在使用的提供商设置凭据对象。

答案 1 :(得分:7)

对于Swift 4:

typealias Completion = (Error?) -> Void 

func changePassword(email: String, currentPassword: String, newPassword: String, completion: @escaping Completion) {
    let credential = EmailAuthProvider.credential(withEmail: email, password: currentPassword)
    Auth.auth().currentUser?.reauthenticate(with: credential, completion: { (error) in
        if error == nil {
            currentUser.updatePassword(to: newPassword) { (errror) in
                completion(errror)
            }
        } else {
            completion(error)
        }
    })
}

可以找到Firebase文档here

答案 2 :(得分:0)

让Swift 5在Firebase中更改密码

import Firebase

func changePassword(email: String, currentPassword: String, newPassword: String, completion: @escaping (Error?) -> Void) {
        let credential = EmailAuthProvider.credential(withEmail: email, password: currentPassword)
        Auth.auth().currentUser?.reauthenticate(with: credential, completion: { (result, error) in
            if let error = error {
                completion(error)
            }
            else {
                Auth.auth().currentUser?.updatePassword(to: newPassword, completion: { (error) in
                    completion(error)
                })
            }
        })
    }

如何使用?

self.changePassword(email: "abcemail@gmail.com", currentPassword: "123456", newPassword: "1234567") { (error) in
        if error != nil {
            self.showAlert(title: "Error" , message: error?.localizedDescription)
        }
        else {
            self.showAlert(title: "Success" , message: "Password change successfully.")
        }
    }