Reputation: 817
I have some problems with changing email address in firebase authentication. My code looks like this now:
func changeEmail(withEmail email: String, completion: @escaping ((Bool) -> Void)) {
guard let currentUser = Auth.auth().currentUser, let email = mail else { return }
currentUser.updateEmail(to: email) { [weak self]
error in
guard let self = self else { return }
let title: String
let message: String
if let error = error {
title = "alert.error.title".localized()
message = error.localizedDescription
} else {
title = email
message = "auth.confirm.email.popup".localized()
currentUser.sendEmailVerification()
}
self.navigator.showAlert(title: title,
message: message,
bottomLeftTitle: "general.got.it".localized(),
bottomLeftHandler: { completion(error == nil)
})
}
}
So it is okey, and working, and user can actually change email.
But problem occurs when user stayed too long and needs to re-login. Everyone knows that it is disturbing user experience in app.
Auth.auth().reload() //not working in this situation.
So how to change email, without asking user to logout and login again?
Upvotes: 1
Views: 284
Reputation: 1850
There is a reauthenticate
method exactly for this purpose.
https://firebase.google.com/docs/auth/ios/manage-users#re-authenticate_a_user
What you need to do is ask the user for its login credentials again. No logout - login needed.
Possible code for that:
if (self.newPassword == self.newPasswordConfirm) && (!(self.newPassword.isEmpty) || !(self.newUserName.isEmpty)) {
reauthenticate(email: self.accountEmail, password: self.oldPassword) { isSucceeded in
//Successfully authenticated
if isSucceeded == true {
if !self.newUserName.isEmpty {
// update username
}
Auth.auth().currentUser?.updatePassword(to: self.newPassword) { (error) in
// Alert user that it didn't work
}
self.editProfile.toggle()
}
// Failed to reauthenticate
else if isSucceeded == false {
// Alert User
}
}
}
Upvotes: 2