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)
}
}
}
Related
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
this is my first question here, i hope you can help me.
I've been trying to get a specific path for the current user logged into my app.
I don't really now what i'm doing wrong so i'll paste my code here.
func userRoleListener() {
guard let user = Auth.auth().currentUser else { return } .
Firestore.firestore().collection("users").document("sjbD5SvKTYHWBLhCqojs").getDocument { (snapshot, error) in
if let data = snapshot?.data() {
guard let isAdmin = data["isAdmin"] as? Bool else { return }
if isAdmin {
self.applyButton.isHidden = true
} else {
self.applyButton.isHidden = false
}
}
}
}
This is my function to create a user.
private func createUser() {
guard let nameAndLastname = nameAndLastnameTextField.text , let email = emailTextField.text , let password = passwordTextField.text , !nameAndLastname.isEmpty , !email.isEmpty , !password.isEmpty else {
simpleAlert(title: "Error", msg: "Debe completar todos los campos")
return
}
let newUserReference = Firestore.firestore().collection("users").document()
newUserReference.setData([
"nameAndLastname": nameAndLastname,
"email": email,
"password": password,
"isAdmin": false,
"timestamp": Timestamp()
])
}
And this is my login action:
#IBAction func signUpButtonPressed(_ sender: Any) {
guard let email = emailTextField.text , let password = passwordTextField.text , !email.isEmpty , !password.isEmpty else { return }
self.signUpButton.animateButton(shouldLoad: true, withMessage: "")
Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
if let error = error {
self.signUpButton.animateButton(shouldLoad: false, withMessage: "¡REGISTRAR!")
debugPrint(error.localizedDescription)
self.simpleAlert(title: "Error", msg: "Error al iniciar sesión, intente nuevamente en unos minutos")
return
}
self.signUpButton.animateButton(shouldLoad: false, withMessage: "")
self.createUser()
self.presentClientStoryboard()
}
}
And this is an image of my database:
Database image
If you create a user with Firebase Authentication, Authentication will create a user and a user id for you in Firebase Auth (Not Firestore)
So when you create your user in Firestore, you have to set the userID as document id, like below:
#IBAction func signUpButtonPressed(_ sender: Any) {
guard let email = emailTextField.text , let password = passwordTextField.text , !email.isEmpty , !password.isEmpty else { return }
self.signUpButton.animateButton(shouldLoad: true, withMessage: "")
Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
if let error = error {
self.signUpButton.animateButton(shouldLoad: false, withMessage: "¡REGISTRAR!")
debugPrint(error.localizedDescription)
self.simpleAlert(title: "Error", msg: "Error al iniciar sesión, intente nuevamente en unos minutos")
return
}
self.signUpButton.animateButton(shouldLoad: false, withMessage: "")
self.createUser(user.uid) // <----- user id from Firebase Auth
self.presentClientStoryboard()
}
}
and
private func createUser(userId: String) {
guard let nameAndLastname = nameAndLastnameTextField.text , let email = emailTextField.text , let password = passwordTextField.text , !nameAndLastname.isEmpty , !email.isEmpty , !password.isEmpty else {
simpleAlert(title: "Error", msg: "Debe completar todos los campos")
return
}
let newUserReference = Firestore.firestore().collection("users").document(userId) // <-- create a document, with the user id from Firebase Auth
newUserReference.setData([
"nameAndLastname": nameAndLastname,
"email": email,
"password": password,
"isAdmin": false,
"timestamp": Timestamp()
])
}
You should get the user id from the current user, try this:
func userRoleListener() {
guard let userUid = Auth.auth().currentUser.uid else { return } .
Firestore.firestore().collection("users").document(userUid).getDocument { (snapshot, error) in
if let data = snapshot?.data() {
guard let isAdmin = data["isAdmin"] as? Bool else { return }
if isAdmin {
// And I believe here the true and false values should be switched as you are checking if the user IS an admin, if they are an admin, shouldn't you show the button?
self.applyButton.isHidden = false
} else {
self.applyButton.isHidden = true
}
}
}
}
This get's the current user logged into the app and then uses the users uid to search the database. Just make sure when you create an account you save the user data accordingly.
I have three text field in my registration form. The e-mail id and password of the user are used by the Firebase SignUp method to create a new user. But I also want to save the user's name according to what they input.
My current code is;
#IBAction func registerPressed(_ sender: Any) {
SVProgressHUD.show(withStatus: "Setting you up")
dismissUIElements(value: false)
let currentUserName = userName.text
if currentUserName?.isEmpty == false {
FIRAuth.auth()?.createUser(withEmail: emailTextField.text!, password: passwordTextField.text!, completion: { (user, error) in
if error != nil {
print(error!)
SVProgressHUD.dismiss()
self.dismissUIElements(value: true)
} else {
print("Registration Successful!")
SVProgressHUD.dismiss()
self.dismissUIElements(value: true)
self.performSegue(withIdentifier: "goToSelectionFromRegister", sender: self)
}
})
}
else {
SVProgressHUD.dismiss()
SVProgressHUD.showError(withStatus: "Please enter your name!")
SVProgressHUD.dismiss(withDelay: 1)
self.dismissUIElements(value: true)
}
}
You need a function that will register the user and then create the child for that user in Firebase.
let databaseRef=//your path to users.
func registerUser(userUsername userName:String, userEmail email:String, userPassword password: String, userCreationComplete: #escaping (_ status: Bool, _ error: Error?) -> ()) {
Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
guard let user = user else {
userCreationComplete(false, error)
return
}
let userData = ["userName": userName.text] as [String : Any]
ref.child(user.uid).updateChildValues(userData)
userCreationComplete(true, nil)
}
}
Then you call the function from within registerPressed() and you pass it the textfield values but make sure that none of them is empty.
You will create a new data table that stores that info. It won't be done in the create user function.
// create a reference to the DB
ref = Database.database().reference(fromURL: "https://your-project-name.firebaseio.com/")
//variables to store data
var myID : String?
var myName : String?
var myNumber : String?
var myEmail : String?
// creating the save user function
func saveUser(_ completion: #escaping(_ error: Error?) -> Void) {
if PageDataSource.sharedInstance.crudIsAvailable == true {
let usersRef = ref.child("users")
let myUserRef = usersRef.child(id)
myUserRef.updateChildValues(["User ID": id,
"Name": myName,
"Email": myEmail,
"Phone": .myNumber], withCompletionBlock: { (error, ref) in
if error != nil {
completion(error!)
} else {
completion(nil)
}
})
} else {
completion(NSError(domain: "Unavailable", code: 0, userInfo: nil))
}
}
// call the method like this to perform the save
func storeUser(completion: #escaping(_ completed: Bool, _ error: NSError?)-> Void) {
if let user = Auth.auth().currentUser {
myID = user.uid
myName = user.displayName
myEmail = user.email
// etc.,
completion(true,nil)
} else {
completion(false,NSError(domain: "No Current User", code: 1, userInfo: nil))
}
}
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.
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)
}
}
})
}
})
}
}
}