Swift: Changing password for user on Firebase - swift

I have three UITextFields, in which I am getting the old password, new password, and confirm password. I am getting the alert success, but my password for the user is not changing. Any ideas? Thanks.
#IBAction func buttonPressed(_ sender: UIButton) {
if password != confirmPassword {
createAlert(title: "Error", message: "Passwords do not match")
} else {
let user = Auth.auth().currentUser
let credential: AuthCredential = EmailAuthProvider.credential(withEmail: (user?.email)!, password: oldPassword!)
user?.reauthenticateAndRetrieveData(with: credential, completion: {(authResult, error) in
if error != nil {
self.createAlert(title: "Error", message: "failed")
}else{
Auth.auth().currentUser?.updatePassword(to: self.password!) { (error) in
print("Error")
}
self.createAlert(title: "Success", message: "Password change successful!")
}
})
}
}

Related

Check Firebase error and if textFields are empty before creating user

I´m trying to check for signup errors and if textFields is empty. This is kind of working, but it allows the user to register the user if the nameTextFieldand the addressTextFieldis empty. The alert poops up correctly though.
#IBAction func registerButton(_ sender: UIButton) {
Auth.auth().createUser(withEmail: emailTextField.text!, password: passwordTextField.text!, completion: { user, error in
if error != nil {
if let errCode = AuthErrorCode(rawValue: error!._code) {
switch errCode {
case .invalidEmail:
self.errorMsg(title: "Error", message: "E-mail address format wrong")
case .emailAlreadyInUse:
self.errorMsg(title: "Error", message: "E-mail is already in use")
case .weakPassword:
self.errorMsg(title: "Error", message: "Weak password. Need at least 6 characters")
default:
print("Create User Error: \(error!)")
}
}
return
} else {
//Display errormsg for missing entry
if (self.nameTextField.text?.isEmpty)! {
self.missingText(title: "Ooops", message: "Please enter your name")
if (self.addressTextField.text?.isEmpty)! {
self.missingText(title: "Ooops", message: "Please enter your address")
}
} else {
//Register userinfo in Firebase
let ref = Database.database().reference()
let usersRefrence = ref.child("users")
let uid = user?.user.uid
let newUserRefrence = usersRefrence.child(uid!)
newUserRefrence.setValue(["Name": self.nameTextField.text!, "Address": self.addressTextField.text!])
}
self.registrationConfirmation(title: "Great", message: "Please sign in with the registered user")
}
})
}
validate textfield before going to auth.
guard let email = emailTextField.text, email.isValidEmail(), let password = passwordTextField.text, password != "" else {
// show error for nil values
return
}
// go with Autth
Auth.auth().createUser(withEmail: email, password: password, completion
make an extension for validating email
extension String {
func isValidEmail() -> Bool {
// here, `try!` will always succeed because the pattern is valid
let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .caseInsensitive)
return regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
}
}

Show Login/Signup Errors with firebase

I want to show the error to the user while logging in if the information is incorrect. Such as invalid username/Password etc
#IBAction func signIn(_ sender: Any) {
Auth.auth().signIn(withEmail: emailTextField.text!, password: passwordTextField.text!) { (user, error) in
if error != nil {
//self.createAlert(titleText: "Error", messageText: String(describing: error?.localizedDescription))
return
} else {
self.performSegue(withIdentifier: "signInToTabBarVC", sender: nil)
print("Signed In")
}
}
}
I also want to show sign up errors. Including email is already in use or username or password is too weak
Auth.auth().createUser(withEmail: emailField.text! , password: passwordField.text!, completion: { (user: User?, error: Error?) in
if error != nil {
print(error!.localizedDescription)
return
}
let uid = user?.uid
let storageRef = Storage.storage().reference(forURL: "gs://vloggle-cb375.appspot.com").child("profile_picture").child(uid!)
if let chosenImg = self.chosenImage, let imageData = UIImageJPEGRepresentation(chosenImg, 0.1) {
storageRef.putData(imageData, metadata: nil, completion: { (metadata, error) in
if error != nil {
return
}
let profileImageUrl = metadata?.downloadURL()?.absoluteString
self.setUserInformation(profileImageUrl: profileImageUrl!, username: self.usernameField.text!, email: self.emailField.text!, uid: uid!)
})
}
})
}
you can show error message with the help of UIAlertView
let dialog = UIAlertController(title: error!.localizedDescription, message: "", preferredStyle: UIAlertControllerStyle.alert)
dialog.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
DispatchQueue.main.async(execute: {
self.present(dialog, animated: true, completion: nil)
})

How to have hashed passwords in Firebase using Swift?

I was following an Uber clone tutorial. I can get log in, registration, and logout working, but the passwords don't seem to be hashed; I can see them plainly in my Firebase database.
Here is my code. First login/sign up/logout function saved in a 'plugins' folder separate from controllers.
import Foundation
import FirebaseAuth
typealias LoginHandler = (_ msg: String?) -> Void;
struct LoginErrorCode {
static let INVALID_EMAIL = "Invalid email, please provide a real email address";
static let WRONG_PASSWORD = "Wrong Password, Please Try Again";
static let PROBLEM_CONNECTING = "Problem Connecting to Database. Please Try Later";
static let USER_NOT_FOUND = "User Not Found, Please Register";
static let EMAIL_ALREADY_IN_USE = "Email Already In Use, Please Use Different Email";
static let WEAK_PASSWORD = "Password Should Be At Least 6 Characters";
}
class AuthProvider {
private static let _instance = AuthProvider();
static var Instance: AuthProvider {
return _instance;
}
func login(withEmail: String, password: String, loginHandler: LoginHandler?) {
FIRAuth.auth()?.signIn(withEmail: withEmail, password: password, completion: { (user, error) in
if error != nil {
self.handleErrors(err: error as! NSError, loginHandler: loginHandler);
} else {
loginHandler?(nil);
}
})
} //login func
func signUp(withEmail: String, password: String, loginHandler: LoginHandler?) {
FIRAuth.auth()?.createUser(withEmail: withEmail, password: password, completion: { (user, error) in
if error != nil {
self.handleErrors(err: error as! NSError, loginHandler: loginHandler);
} else {
if user?.uid != nil {
// store the user to database
DBProvider.Instance.saveUser(withID: user!.uid, email: withEmail, password: password)
//log in the user
self.login(withEmail: withEmail, password: password, loginHandler: loginHandler)
}
}
})
} //sign up func
func logOut() -> Bool {
if FIRAuth.auth()?.currentUser != nil {
do {
try FIRAuth.auth()?.signOut();
return true;
} catch {
return false;
}
}
return true
}
private func handleErrors(err: NSError, loginHandler: LoginHandler?) {
if let errCode = FIRAuthErrorCode(rawValue: err.code) {
switch errCode {
case .errorCodeWrongPassword:
loginHandler?(LoginErrorCode.WRONG_PASSWORD);
break;
case .errorCodeInvalidEmail:
loginHandler?(LoginErrorCode.INVALID_EMAIL);
break;
case .errorCodeUserNotFound:
loginHandler?(LoginErrorCode.USER_NOT_FOUND);
break;
case .errorCodeEmailAlreadyInUse:
loginHandler?(LoginErrorCode.EMAIL_ALREADY_IN_USE);
break;
case .errorCodeWeakPassword:
loginHandler?(LoginErrorCode.WEAK_PASSWORD);
break;
default:
loginHandler?(LoginErrorCode.PROBLEM_CONNECTING);
break;
}
}
}
} //class
And the controller:
import UIKit
import FirebaseAuth
class SignInVC: UIViewController {
private let DRIVER_SEGUE = "DriverVC";
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func login(_ sender: Any) {
if emailTextField.text != "" && passwordTextField.text != "" {
AuthProvider.Instance.login(withEmail: emailTextField.text!, password: passwordTextField.text!, loginHandler: { (message) in
if message != nil {
self.alertTheUser(title: "Problem With Authentication", message: message!);
} else {
self.performSegue(withIdentifier: self.DRIVER_SEGUE, sender: nil)
}
});
} else {
alertTheUser(title: "Email And Password Are Required", message: "Please enter email and password");
}
}
#IBAction func signUp(_ sender: Any) {
if emailTextField.text != "" && passwordTextField.text != "" {
AuthProvider.Instance.signUp(withEmail: emailTextField.text!, password: passwordTextField.text!, loginHandler: { (message) in
if message != nil {
self.alertTheUser(title: "Problem With Creating New Account", message: message!)
} else {
self.performSegue(withIdentifier: self.DRIVER_SEGUE, sender: nil)
}
})
} else {
alertTheUser(title: "Email And Password Are Required", message: "Please enter email and password");
}
}
private func alertTheUser(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert);
let ok = UIAlertAction(title: "OK", style: .default, handler: nil);
alert.addAction(ok);
present(alert, animated: true, completion: nil)
}
} //class
Try using updatePassword(_ password: String, completion: FirebaseAuth.FIRUserProfileChangeCallback? = nil) on FIRUser.

Swift: Using credentials with Firebase and a additional textfield for username

I have a few things I'm trying to accomplish. First, my email and password don't matter if they're filled or not to login. I would like the app to check if email and password is filled and correct before logging in. Secondly, I would like to put in a username when they register so it would show up on the profile page and tell other users who they're without revealing an email address. I'm using Firebase and I thought this would do the trick, but it doesn't. I looked over this Stack overFlow Post and have everything correct I think, but its still letting you login without credentials.
#IBAction func loginRegisterBtnPressed(_ sender: AnyObject) {
performSegue(withIdentifier: "profileVC", sender: self)
if let email = emailTextField.text, let password = passwordTextField.text {
FIRAuth.auth()?.signIn(withEmail: email, password: password, completion: { (user, error ) in
if error == nil {
print("DAW: User Created")
} else {
FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user, error ) in
if error != nil {
print ("DAW: User failed to authenticate with Firebase")
} else {
print ("DAW: Successfully")
if let user = user {
self.completeSignIn(id: user.uid)
}
}
})
}
})
}
}
#IBAction func loginRegisterBtnPressed(_ sender: AnyObject) {
if let email = emailTextField.text, let password = passwordTextField.text {
if email != "" && password != ""{
FIRAuth.auth()?.signIn(withEmail: email, password: password, completion: { (user, error ) in
if error == nil {
performSegue(withIdentifier: "profileVC", sender: self)
} else {
FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user, error ) in
if error != nil {
print ("DAW: User failed to authenticate with Firebase")
} else {
print ("DAW: Successfully")
if let user = user {
self.completeSignIn(id: user.uid)
}
}
})
}
})
}
}
}

Swift 2.0 Parse Login

So I've been attempting to update my code to Swift 2.0 syntax, but I can't seem to get my Parse login to work. I looked over the documentation changes and added the result block for my login, but I'm getting the error "'(, ) throws -> Void' is not convertible to 'PFUserResultBlock?'"
Here is the line of code:
PFUser.logInWithUsernameInBackground(usernameTextField.text!, password: passwordTextField.text!, block: { (user,error) -> Void in
if user != nil {
This Code might solve your problem.
PFUser.logInWithUsername(inBackground: emailTextField.text!, password: passwordTextField.text!, block: { (user, error) in
self.activityIndicator.stopAnimating()
UIApplication.shared.endIgnoringInteractionEvents()
if error != nil {
var displayErrorMessage = "Please try again later"
let error = error as NSError?
if let errorMessage = error?.userInfo["error"] as? String {
displayErrorMessage = errorMessage
}
self.createAlert(title: "Login Error", message: displayErrorMessage)
} else {
print("logged inn")
self.performSegue(withIdentifier: "showUserTable", sender: self)
}
})
Try this version
PFUser.logInWithUsernameInBackground(usernameTextField.text!, password: passwordTextField.text!) { (user:PFUser?, error:NSError?) -> Void in
if user != nil {
print("Login Successful")
} else {
print("Login Failed")
}
}