How to verify user's current password when changing password on Firebase 3?
You will be able to achieve it using reauthenticate before changing the password.
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
}
})
Just to add more information, here you can find how to set the credential object for whatever provider you are using.
For 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 Documentation can be found here
For Swift 5 to change password in 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)
})
}
})
}
How to use ?
self.changePassword(email: "[email protected]", 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.")
}
}