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

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)
}
}
})
}
})
}
}
}

Related

Does not add a user to Firebase

I am trying to add users to my Firebase cloud
I connected my project to the console.firebase
While I fill in the email and password it is not adding to my firebase.
I have the following code:
#IBAction func registerButton(_ sender: Any) {
signUp()
}
this is a button for register
and this is the func signup:
func signUp (){
let name = nameValue.text
let password = passwordValue.text
let email = emailValue.text
if (!password!.isEmpty && !email!.isEmpty) {
Auth.auth().createUser(withEmail: email ?? "", password: password ?? "") { (result, error) in
if error == nil {
if let result = result {
}
}
}
}
else {
showAlert()
}
}
Can anybody help to figure out this problem?
here is the solution to my problem:
if (!name!.isEmpty && !password!.isEmpty && !email!.isEmpty) {
Auth.auth().createUser(withEmail: email ?? "", password: password ?? "") { (authResult, error) in
if let e = error {
print(e.localizedDescription)
} else {
// self.performSegue(withIdentifier: "main", sender: self)
}
}
}

self.userUid = user.user.uid method still not working in Swift

Ok so in my code I get this error:'Value of type 'AuthDataResult' has no member 'uid''. Even after trying to use the authDataResult or the self.userUid = user.user.uid, I'm still getting the error. Here's my code if anyone wants to help me
#IBAction func SignIn (_ sender: AnyObject) {
if let email = emailField.text, let password = passwordField.text {
Auth.auth().signIn(withEmail: email, password: password, completion: { (user, error) in
if error == nil {
self.userUid = user.user.uid
KeychainWrapper.standard.set(self.userUid, forKey: "uid")
self.performSegue(withIdentifier: "toMessages", sender: nil)
} else {
self.performSegue(withIdentifier: "toSignUp", sender: nil)
}
})
}
}
Thanks if you can help me!
Inside if error == nil { do the following :
let user = Auth.auth().currentUser
if let user = user {
// The user's ID, unique to the Firebase project.
// Do NOT use this value to authenticate with your backend server,
// if you have one. Use getTokenWithCompletion:completion: instead.
let uid = user.uid
let email = user.email
}
You can find more information here:
https://firebase.google.com/docs/auth/ios/manage-users

Swift: Changing password for user on Firebase

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!")
}
})
}
}

Cannot assign to value: 'user' is a 'let' constant - FIXED

I am trying to create a login page where user logs in with Auth Email/Password and if they are declared admin or user the performSegue takes to a different page.
Here is my code:
#IBAction func submit(_ sender: UIButton) {
if let email = txtemail.text, let passowrd = txtpass.text {
Auth.auth().signIn(withEmail: email, password: passowrd) { (user, error) in
Database.database().reference().child("user").child("admin")
if user = true {
self.performSegue(withIdentifier: "adminlogin", sender : self)
}
if user = false {
self.performSegue(withIdentifier: "login", sender : self)
}
}
}
However keeps coming up with this error:
Cannot assign to value: 'user' is a 'let' constant
ANSWERED:
I fixed this by doing this to my code:
{ Auth.auth().signIn(withEmail: email, password: passowrd) { (user, error) in
if user != nil {
let uid = Auth.auth().currentUser?.uid
Database.database().reference().child("user").child(uid!).child("admin").observeSingleEvent(of: .value, with: { (snapshot) in
// Checking if user is found
if snapshot.exists() {
// admin is found
self.performSegue(withIdentifier: "adminlogin", sender : self)
} else {
// admin is not found going to user login
self.performSegue(withIdentifier: "login", sender : self)
}
})
Now when I log in with Admin I go to another View Controller, than if I log in with a User.
= is used as an assignment operator
== is the comparison operator
You want to use == to make the comparison.
The user and error objects are immutable, meaning you can't change them. But they are holding values that you want to check.
I've updated your code to work:
#IBAction func submit(_ sender: UIButton) {
if let email = txtemail.text, let passowrd = txtpass.text
{
Auth.auth().signIn(withEmail: email, password: passowrd) { (user, error) in
Database.database().reference().child("user").child("admin")
if user == true {
self.performSegue(withIdentifier: "adminlogin", sender : self)
}
if user == false {
self.performSegue(withIdentifier: "login", sender : self)
}
}
}
}
You have put if user = true A single = is an assignment. To check a value is equal to something use if user == true
You can't check if the user is an admin or not by comparing it to true or false. I suggest to log the user in and after that validating if the UID is an admin by so:
let databaseRef = Database.database().reference(withPath: "user/admin/(UID after logged in)")
databaseRef.observeSingleEvent(of: .value, with: { (snapshot) in
// Checking if user is found
if snapshot.exists() {
// admin is found
self.performSegue(withIdentifier: "adminlogin", sender : self)
} else {
// admin is not found going to user login
self.performSegue(withIdentifier: "login", sender : self)
}
})

how to prevent a new user from login until they verify their email in firebase swift?

when user register by email they get validation link to the email they provided for users to verify it. I want users who did not validate their email not be able to login or go to main screen till they verify their email. here is my code.
#IBAction func emailRegisterButtonPressed(_ sender: Any) {
if emailTextField.text != "" && nameTextField.text != "" && lastnameTextField.text != "" && passwordTextField.text != "" {
FUser.registerUserwith(email: emailTextField.text!, password: passwordTextField.text!, firstName: nameTextField.text!, lastName: lastnameTextField.text!, completion: {(error) in
if error != nil {
print (" Error registering user with email: \(error?.localizedDescription)")
return
}
Auth.auth().currentUser?.sendEmailVerification { (error) in
// ...
ProgressHUD.showSuccess("please validate your email")
}
})
}
}
#IBAction func loginVC(_ sender: Any) {
if ( email is not verified << Code here ) {
ProgressHUD.showSuccess("please verify your email ")
} else {
go to main app or (login)
}
}