Update a User's Firebase password in Swift - ios

I have a UITableViewController and I'd like the user to be able to change their current password with a new one.
The view is very straight forward - 2 UITextFields where I'd like them to enter their current password and another one for their desired new password.
The problem is I cannot find in Firebase's documentation a method that does that. Does anyone have an idea how to accomplish this?
PS: Ignore that it says "Update your email", this will be fixed.

1. Change Password
In Order to change password for Firebase User you do not need old password. You can do it by re-authenticating user and then updating password.
i. Re-authenticate User:
let user = Auth.auth().currentUser
var credential: AuthCredential
// Prompt the user to re-provide their sign-in credentials
user?.reauthenticate(with: credential) { error in
if let error = error {
// An error happened.
} else {
// User re-authenticated.
}
}
https://firebase.google.com/docs/auth/ios/manage-users#re-authenticate_a_user
ii. Change Password
Once user is re-authenticated use following method to Change password:
Auth.auth().currentUser?.updatePassword(to: password) { (error) in
// ...
}
2. Forgot Password
To handle this case you can send password reset link to user's email. Use following method:
Auth.auth().sendPasswordReset(withEmail: email) { error in
// ...
}
source: https://firebase.google.com/docs/auth/ios/manage-users

Related

How to detect if an email address change was reverted?

I was working on the user profile page of my app and I am allowing the user to change their email address. If the user email address is changed successfully, the data in the firebase database of the particular user will be updated. Also, After successfully changing the email address, firebase will send an email to the user's previous email address (the user email address before it was changed to the new one) asking if it was the actual owner of the account who changed the email address and there will be a link to reset their email. If the user chooses to reset the email (for whatever reason), the user's new email will be changed to the previous email. But the problem is that the data in the database will not be updated, how can I detect this change (email reset) and update the database?
authenticateUserAlert.addAction(UIAlertAction(title: "Done", style: .default, handler: { [weak authenticateUserAlert] (_) in
// Print the user email
let emailTextField = authenticateUserAlert?.textFields![0]
print("Email: \(emailTextField!.text!)")
// Print the user password
let passwordTextField = authenticateUserAlert?.textFields![1]
print("Password: \(passwordTextField!.text!)")
// Re-authenticate the user
let user = Auth.auth().currentUser
let credential = EmailAuthProvider.credential(withEmail: emailTextField!.text!, password: passwordTextField!.text!)
user?.reauthenticate(with: credential, completion: { (result, error) in
if error != nil {
// Alert: What ever the error
print(error!.localizedDescription)
Alerts.errorAlert(on: vc, error: error!.localizedDescription, dismissAlert: false)
} else {
print(result!)
let editProfilePage = EditUserProfile()
editProfilePage.updateUserInfo()
}
})
}))
Here is what I tried according to an answer
Auth.auth().currentUser?.reload(completion: { (Error) in
//Completion handler
if let email = Auth.auth().currentUser?.email {
UserDataRetrieval.userEmail = email
self.emailLabel.text = email
print(Auth.auth().currentUser?.email)
}
})
It depends on the type of authentication you are using but honestly you should just use the email that is part of the authenticated account and then you don't need to worry about updating it in the database.
You can always just get the users email by using Auth.auth().currentUser.email
Update
Found a workaround to the issue of the credential data, try using
Auth.auth().currentUser?.reload(completion: { (Error) in
if (Error != nil) {
//Do something with error
} else {
//Do something with success or do nothing
}
})
Just call update credentials at the start of the app if you want to always have to most up to date credentials
You can always build your own custom handler for the email change revocation landing page. In that landing page you can update your database.
Check the official docs on how to do that.

How to set up Firebase iOS authentication email

Having looked through lots of previous questions and looking on the Firebase website documentation, it keeps leading me back to the snippet of code I need in my VC, BUT not how to actually set it up?.
Firstly in the email address verification setup on Firebase
I've by mistake put my personal email address as the 'reply to' email - do I put my personal (not business) email in there/how would I change it? Apologies for any over the top censoring (not sure what is private and not)
Secondly in my SignUpViewController what do I put as the URL String and what do I put as my IOSBundleID? Many thanks!
To change the email go to Authentication and press templates. There you have some options for your mail.
Press the pen beside noreply#yourfirebase.firebaseapp.com.
There you will have a replay to line and you can change all those settings
This is all you need to register a new user :
Auth.auth().createUser(withEmail: emailText.text!, password: passwordText.text!) {
(user, error) in
if error != nil {
print(error.localizedDescripton)
}else {
print("registration successful")
}
}
To send confirmation email to user make a call after user is created and use this method :
func sendConfirmationEmail() {
// Here you check if user exist
if self.authUser != nil && !self.authUser!.isEmailVerified {
self.authUser!.sendEmailVerification(completion: { (error) in
// Send the email
})
}
else {
// ERROR
}
}
You could now call the second method after user been created and the user will get an email

Firebase phone Authenication iOS

I am currently authenticating users using firebase phone Authentication and it works fine, however when I close the app and open it again I am redirected to the Authentication form and I receive an authentication Code each time. I don't want that kind of behavior. Is there is a way to check if the current user or the phone number is already authenticated without saving the user to a database
You can do it like checking for the currentUser in firebase, if the currentUser's phone number is same as the provided phone number in textField, then you can bypass the authentication and take user to home screen. Here is how it can be done.
if Auth.auth().currentUser != nil {
// USER IS SIGNED IN, BUT STILL WE HAVE TO CHECK, IF THE SAME USER IS SIGNING IN OR DIFFERENT.
if let user = Auth.auth().currentUser {
let phone = user.phone
if phone == YOUR TEXTFIELD VALUE OF PHONE {
// YOU HAVE THE LOGGED IN USER NOW, YOU CAN TAKE USER TO HOME SCREEN
} else {
// SIGNOUT THE CURRENT USER AND DO THE AUTHENTICATION FOR NEW USER
let firebaseAuth = Auth.auth()
do {
try firebaseAuth.signOut()
} catch let signOutError as NSError {
print ("Error signing out: %#", signOutError)
}
// No USER IS SIGNED IN, SO GET CREDENTIAL FROM YOUR SERVER AND SEND IT TO AUTH
Auth.auth().signIn(withCustomToken: customToken ?? "") { (user, error) in
// YOU HAVE THE LOGGED IN USER NOW, YOU CAN TAKE USER TO HOME SCREEN
}
}
}
} else {
// No USER IS SIGNED IN, SO GET CREDENTIAL FROM YOUR SERVER AND SEND IT TO AUTH
Auth.auth().signIn(withCustomToken: customToken ?? "") { (user, error) in
// YOU HAVE THE LOGGED IN USER NOW, YOU CAN TAKE USER TO HOME SCREEN
}
}
Check the procedure, if this is what you wants to achieve.

Password Change Parse swift

I have an app that allows a user to reset their password by putting their old one in a textfield and their new one in the next textfield. But in the old password textfield, the password they entered has to match the one that is registered to the currently logged in user. My app keeps crashing. Can someone help me. Here is the code. An image of the error is here.
if Password.text == (PFUser.current()?.password)! {
}else{
}
Try to add exclamation after the text: -
if Password.text! == (PFUser.current()?.password)! {
}else{
}
Edit: -
There is no way to get old password from Parse. Workaround though is.. you can first try authenticate user by giving the password which user has entered.. if authentication is successful then that means the entered old password is correct.. has been described here. Although it is android code it gives the required logic.
ParseUser.logInInBackground(ParseUser.getCurrentUser().getUsername(), currentPassword, new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
// Hooray! The password is correct
} else {
// The password was incorrect
}
}
});

Firebase Facebook login check if user exist

I have an facebook login system which works with firebase but I want to check if user exist on my firebase (i don't want to add it, just want to make sure if he exist because I want to redirect user to another page to complete its profile, once its done I'll want to send it to firebase).
I just need to check if user exist on my db. Here is the code that I try but it returns nil error and it automatically add user to firebase.
let credential = FIRFacebookAuthProvider.credentialWithAccessToken(FBSDKAccessToken.currentAccessToken().tokenString)
FIRAuth.auth()?.signInWithCredential(credential) { (user, error) in
// ...
}
You can use reauthenticateWithCredential method to check user is exist or not.
Check this Doc. , section -> Re-authenticate a user
let user = FIRAuth.auth()?.currentUser
var credential: FIRAuthCredential
// Prompt the user to re-provide their sign-in credentials
user?.reauthenticateWithCredential(credential) { error in
if let error = error {
// An error happened.
} else {
// User re-authenticated.
}
}
If user re-authenticated successfully that means user is existed...

Resources