Firebase How to verify an email to log in belongs to which category in database? - swift

I am working on new Firebase Log in. There are two categories in database. "Cooks" and "Customer". "Cooks" has a CookViewController and "Customers" has a customerViewController. I need to know which category this email belongs to so after logging in, segue to CookViewController or CustomerViewController. Below is code for sign in, but I have no idea how to tell which category the email belongs to. Thanks!
#IBAction func loginPressed(sender: AnyObject) {
if let email = emailField.text where email != "", let password = passwordField.text where password != "" {
FIRAuth.auth()?.signInWithEmail(email, password: password, completion: { (user, err) in
if err != nil {
print(err)
} else {
// Here I need to know whcih view Controller to Segue to:
self.performSegueWithIdentifier(identifier: String, sender: self)
}
}
Data Structure as below:

How about making your JSON like :-
yourApp:{
cooks:{
email1:true,
email3:true,
email4:true,
email7:true,
email8:true},
customers:{
email2:true,
email12:true,
email13:true,
email4:true,
email8:true},
users:{
uid1:{
email : blah#blah.com,
isCook: true
},
uid2:{
email : burp#blah.com,
isCook: false
}....
}
}
So you can either check in the cooks section or the customer section or the uid under users section itself and then relating to the isCook node, if he is ->Go to cookViewController, else go to customerViewController
Easiest way would be to check in the uid:-
FIRDatabase.database().reference().child("users/\(FIRAuth.auth()!.currentUser!.uid)/isCook").observeSingleEventOfType(.Value,withBlock:{(snap) in
if let isThisUserCook = snap.value as? Bool //or String{
if isThisUserCook == true{
//segue to cookVC
}else{
//segue to customerVC
}
}
})

Related

iOS Google Auth: "The password is invalid or the user does not have a password"

My app has three login options: email, google, and facebook, all via Firebase. Everything works perfectly except for logging in eith email.
Recreate the problem
Create a user with email (first name, last name, email, password), (lets say with the email, test1#gmail.com)
Sign out and return back to login page
Sign in with google using the same email (test1#gmail.com)... this will give an alert that says that a user already uses that email. It does not redirect user to the home screen.
Sign in with email again (same email and password)
User cannot sign in now. User is shown the warning that "The password is invalid or the user does not have a password"
In Firebase Authentication, the user who used to have an email sign next to it now has a Google sign next to it. However, in Firestore, the firstName, lastName, email, password, and uid is still stored.
My code
Sign in with Google
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if let err = error {
print("Failed to log into Google: ", err)
return
}
print("Successfully logged into Google")
guard let authentication = user.authentication else { return }
let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken)
// sign user in with Firebase
Auth.auth().signIn(with: credential, completion: { (user, error) in
let firstName = user?.user.displayName
let email = user?.user.email
let lastName = ""
let uid = user?.user.uid
if let err = error {
print("Failed to create a Firebase User with Google account: ", err)
return
} else {
// Successfully logged in
print("Successfully logged into Firebase with Google email: ", email ?? "", "Now add user to Firestore if user is new.")
// check if user already exists
self.addUserToFirestore(firstName ?? "", lastName, email ?? "", uid ?? "", "Google")
}
})
}
func addUserToFirestore(_ firstName:String, _ lastName:String, _ email:String, _ uid:String, _ signInMethod:String) {
let db = Firestore.firestore()
let docRef = db.collection("users").document(uid)
// check if user exists in firestore
docRef.getDocument { (document, error) in
if let document = document {
if document.exists {
let message = "Good news! You already have a Coal account that uses " + email + ".\nPlease sign in to your existing account. Then you will be able to link your " + signInMethod + " profile from your Account Settings page."
// user exists. send to chats screen.
print("User already exists. Document data: \(String(describing: document.data()))")
self.showError("You're already a member!", message)
} else {
// user does not exist. create a new user
print("Document does not exist. Create new user.")
docRef.setData(["firstname":firstName, "lastname":lastName, "email":email]) { err in
if err != nil {
// Show error message
print("Error saving user data to Firestore")
} else {
print("New user created in Firestore")
self.transitionToConvo()
}
}
}
}
}
}
Sign in with email function
// Signing in the user
Auth.auth().signIn(withEmail: email, password: password) { (result, error) in
if error != nil {
// Couldn't sign in
self.loginErrorLabel.text = error!.localizedDescription
self.loginErrorLabel.alpha = 1
}
else {
// user signed in successfully, go to TabBarController
print("User signed in")
let tabBarC = self.storyboard?.instantiateViewController(withIdentifier: "mainTabBarController") as! TabBarController
tabBarC.modalPresentationStyle = .fullScreen
self.present(tabBarC, animated: true, completion: nil)
print("Switched to TabBarController")
}
}
Sign up with email
// Create the user
Auth.auth().createUser(withEmail: email, password: password) { (result, err) in
// there is an error creating user
if err != nil {
self.showErrorLeft("There was an issue creating your account.\n\nPossible reasons for this isssue:\n1) Your email is not formatted correctly.\n2) You already have a Coal account that uses " + email + ". Please sign in to your existing account.\n\nIf you think this is a mistake, please contact as at coal.britto#gmail.com.")
}
else {
let uid = result!.user.uid
// User was created successfully, now store the first name, last name, email
print("new email created in firestore", uid)
db.collection("users").document(uid).setData(["firstname":firstName, "lastname":lastName, "email":email, "password": password, "uid":uid]) { err in
if err != nil {
// Show error message
print("Error saving user data to Firestore")
} else {
print("New user created in Firestore")
self.transitionToConvo()
}
}
// Transition to the chats screen
self.transitionToConvo()
}
}
A User signing in with Google on an E-Mail address that already exists as an E-Mail/PW User will not throw an error. Instead the user is transitioned into a Google Signin User.
So the behaviour you experience is intended by Firebase.
The reason why the password etc. is still stored in your firestore database is because you dont overwrite it with the new data in your code.
Your code after a Google signin sees that there is a document for that user already (the one you created in your createUser function) so nothing happens in your db.
NOTE: Please do not store clear text passwords in your database.

Document ID retrieval

this is supposed to take the user ID from the result!.user.uid and store it a variable or function in order for me to use it again.
the problem is that I dont know how to get it to store the value outside of this function.
Ive tried to make it store to a variable outside of the initial button function, and Ive also tried to return it outside of the function by removing a part of the code which made it become a void. Im not sure where i need to go/what else I can try and do in order to fix this problem.
If anybody know how do I retrieve my document ID from this code your help would be greaty appreciated
#IBAction func NextButtonTapped(_ sender: Any) {
//validate the fileds
let Error = validateFields()
if Error != nil {
// there is somthing wrong with the fields show error message
showError(Error!)
}
else {
// create cleaned versions of the data
let Password = PasswordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let Email = EmailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let Firstname = FirstnameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let Lastname = LastnameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let Age = AgeTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
// create the user
Auth.auth().createUser(withEmail: Email, password: Password) { (results, Err) in
// check for errors
if Err != nil {
// there was an error creating the user
self.showError("Error creating user")
}
else {
// user was created succesfully store first and last name
let db = Firestore.firestore()
db.collection("users").document(results!.user.uid).setData(["first name":Firstname, "last name":Lastname, "age":Age, "uid":results!.user.uid]) { (Error) in
if Error != nil {
// show error message
self.showError("error saving user data")
}
//showing users document id
}
//transition to the home screen
self.transitionToHome()
}
}
}
}
I have no idea what to do any help would be amazing,
thank you very much!!!!
Define a uid variable outside of the IBAction function like so.
var uid: String? = nil
Then, within the createUser function
self.uid = results!.user.uid

How do I grab credential values for re authentication? (Question updated)

I am trying to allow users to change their email or password. I did some research on how re authentication work, most of the questions I had were answered however when creating the credential how do I grab the users email / password in the .credentialWithEmail(email, password: password) section? I'm not sure what to enter in those fields.
When I take a look at the quick help tab, it explains the Parameters:
email
The user's email address.
password
The user's password.
Here is the code
let credential = FIREmailPasswordAuthProvider.credentialWithEmail(email, password: password)
func updateEmail() {
guard let updatedEmail = self.updatedEmail else { return }
let user = Auth.auth().currentUser
guard let currentUid = Auth.auth().currentUser?.uid else { return }
// re authenticate the user
user?.reauthenticate(with: credential, completion: { (result, error) in
if let error = error {
// An error happened.
print(error._code)
self.handleError(error)
} else {
guard self.emailChanged == true else { return }
user?.updateEmail(to: self.emailTextField.text!, completion: { (error) in
if let error = error {
self.handleError(error)
} else {
print("Email Change Success")
USER_REF.child(currentUid).child("email").setValue(updatedEmail) { (err, ref) in
self.dismiss(animated: true, completion: nil)
}
}
}
)}
}
)}
If you are asking why you can't get the email or password after you set FIREmailPasswordAuthProvider, it is because it is set only. There is no function to retrieve email/password after you set FIREmailPasswordAuthProvider. Firebase does not have a way to retrieve set passwords from their Auth class. The user email can be retrieved with let userEmail = Auth.auth().currentUser?.email
You may need to redesign you code to allow the app to save passwords locally using NSUserDefaults or simply make the user reenter them.

Having trouble with query-based Realms

Sorry, my subject isn't very specific.
I'm dealing with managing multiple users in my realm and having some problems. I have a user register with their email and name, then when realm logs in and creates a SyncUser, I create a new YpbUser object with the email, name, and SyncUser.current.identity in YpbUser.id.
When a user logs in, I want to use their email to look up whether there's an existing YpbUser for their email. I'm doing it this way so in the future if someone uses username/password and then uses Google auth (not yet implemented), those SyncUsers can get to the same YpbUser.
Below is my code for checking for an existing YpbUser, along with my realm setup code. The problem I'm having is that it usually, but not always, fails to find a YpbUser even if that user exists (I'm looking at the YpbUser list in realm studio and the user with that email is definitely there!)
Inspecting from within existingUser(for:in:), users is usually 0, but it sometimes non-zero.
I assume the issue lies somewhere in the fact that I'm pretty much just guessing on how to use SyncSubscription.observe.
Please help?
fileprivate func openRealmWithUser(user: SyncUser) {
DispatchQueue.main.async { [weak self] in
let config = user.configuration(realmURL: RealmConstants.realmURL, fullSynchronization: false, enableSSLValidation: true, urlPrefix: nil)
self?.realm = try! Realm(configuration: config)
let songSub = self?.realm?.objects(Song.self).subscribe()
let usersSub = self?.realm?.objects(YpbUser.self).subscribe()
self?.usersToken = usersSub?.observe(\.state, options: .initial) { state in
if !(self?.proposedUser.email.isEmpty)! {
self?.findYpbUser(in: (self?.realm)!)
}
}
self?.performSegue(withIdentifier: Storyboard.LoginToNewRequestSegue, sender: nil)
}
}
fileprivate func findYpbUser(in realm: Realm) {
if proposedUser != YpbUser() { // self.proposedUser.email gets set from the login method
let existingUser = YpbUser.existingUser(for: proposedUser, in: realm)
guard existingUser == nil else { // If we find the YpbUser, set as current:
try! realm.write {
pr("YpbUser found: \(existingUser!)")
YpbUser.current = existingUser }
return
}
pr("YpbUser not found.") // i.e., SyncUser set, but no YpbUser found. i.e., creating a new YpbUser
createNewYpbUser(for: proposedUser, in: realm)
}
}
extension YpbUser {
class func existingUser (for proposedUser: YpbUser, in realm: Realm) -> YpbUser? {
let users = realm.objects(YpbUser.self)
let usersWithThisEmail = users.filter("email = %#", proposedUser.email)
if let emailUser = usersWithThisEmail.first {
return emailUser
}
return nil
}
}

Unique usernames in Firebase

I have been trying to implement Chris’ answer here: Can I make Firebase use a username login process? for the Facebook login but I can’t seem to get my head around it.
So far I’ve tried to set conditions on the textField but as Firebase observer works asynchronously, the conditions to check if the username exists in the database won’t work.
let usernameString = usernameTextField.text
let uid = FIRAuth.auth()?.currentUser?.uid
ref.runTransactionBlock({ (currentData: FIRMutableData) -> FIRTransactionResult in
if var post = currentData.value as? [String : AnyObject], let uid = FIRAuth.auth()?.currentUser?.uid {
let usernamesDictionary = post["usernames"] as! NSDictionary
for (key, _) in usernamesDictionary {
if key as? String == usernameString {
print("username not available: \(key)")
}
else if usernameString == "" {
print("Uh oh! Looks like you haven't set a username yet.")
}
else if key as? String != usernameString {
print("username available: \(key)")
print("All set to go!")
let setValue: NSDictionary = [usernameString!: uid]
post["usernames"] = setValue
currentData.value = post
}
}
return FIRTransactionResult.successWithValue(currentData)
}
return FIRTransactionResult.successWithValue(currentData)
}
Then I tried creating /usernames/ node in the database and set up rules as:
{
"rules": {
"usernames": {
".read": "auth != null",
".write": "newData.val() === auth.uid && !data.exists()"
}
}
}
Now that won’t let me set any username to the database. I get confused in creating rules but my whole point is that I need a sign up flow with the username data that’s unique for each user in the database.
While trying every answer I found in related posts, what worked for me the easy way i.e. without making Firebase rules play a part in it or creating a separate usernames node in the database was to not put an if/else condition inside the Firebase observer but instead to use the exists() method of FIRDataSnapshot.
Now here’s the trick, while I did try only the exists() method with a simple observer but that did not help me. What I did was first query usernames in order, then match the username with queryEqualToValue to filter the query:
refUsers.queryOrderedByChild("username").queryEqualToValue(usernameString).observeSingleEventOfType(.Value , withBlock: {
snapshot in
if !snapshot.exists() {
if usernameString == "" {
self.signupErrorAlert("Uh oh!", message: "Looks like you haven't set a username yet.")
}
else {
// Update database with a unique username.
}
}
else {
self.signupErrorAlert("Uh oh!", message: "\(usernameString!) is not available. Try another username.")
}
}) { error in
print(error.localizedDescription)
}
}
This is the first time out of most of the answers here that worked for me. But for now, I don’t know if this would scale. Post your experiences and best practices. They’ll be appreciated.