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

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.

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.

How to access Firebase Firestore data when login in using Firebase Auth?

On an application I'm building, I need to access the stored documents on Firestore after someone logs in using Auth. I have stored data on Firestore when someone creates an account: name, phone, email. I want to access this information when they log back in somewhere else. Is there a way to link the two on account creation or is there some other way to access the documents?
After looking around on the internet for a while, I haven't found any questions related to this, other than trying to login using Firestore, but it had no answers.
Account creation code:
Auth.auth().createUser(withEmail: email.text!, password: pass.text!) { (user, error) in
if user != nil {
self.performSegue(withIdentifier: "toFinishCreation", sender: self)
} else {
}
}
Storing data on Firestore:
FirebaseFirestore.root.collection("users").document(username).setData([
"name": username,
"phone": userphone,
"email": useremail], completion: { (err) in
if let err = err {
print(err.localizedDescription)
} else {
print("Document added!")
}
}
)
(Btw I used a struct on another swift file using vars called FirebaseFirestore and root)
Login code:
Auth.auth().signIn(withEmail: loginEmail.text!, password: loginPassword.text!) { (user, error) in
if user != nil {
self.performSegue(withIdentifier: "toHome", sender: self)
} else {
}
}
To summarize, how do I access the data that I stored on account login?
Can anyone help me with this? Anything is appreciated!
To fetch a document of the logged-in user you required document id which is unique. So, add user id as a document id. You will get user id in response while logged in and sign up and then, you can use that id to fetch logged in the user's document.
When creating a user, create a new Auth in FirebaseAuth as well as the Firestore. Once the user is logged in with the email address, find the user with that email. Although I have not used firestore before, note that this code is done with firebase database instead but the same should apply:
Auth.auth().createUser(withEmail: email, password: password, completion: { (user: User?, error) in
if error == nil {
print("You have successfully signed up")
guard let uid = user?.uid else {
return
}
//successfully authenticated user
let values = ["name": name, "email": email, "isShop" : shopAccount]
let ref = Database.database().reference()
let usersReference = ref.child("users").child(uid)
usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in
ref.child("Orders").child("Total Orders").setValue(0)
let vc = self.storyboard?.instantiateViewController(withIdentifier: "MainPageViewController")
self.present(vc!, animated: true, completion: nil)
})
This will then create a user in the FirebaseAuth, and add a new user to the Users section of the database under the uid that is assigned when the account is created. Then you can access this later when the user logs back in as you can retrieve the uid, and find the part of the database containing the information using this code:
dataRef.child("users").child(userID!).observeSingleEvent(of: .value, with: {(snapshot) in
As a result, this can be applied to firestore by adding a new document and title to each user added to your FirebaseAuth in order to retrieve future information

How to get username from AWS Cognito - Swift

Q & A Style: See Answer Below
How Can I get the username from a user logged in with Cognito?
I've done this and my user is logged in, now what?
AWSAuthUIViewController.presentViewController(
with: self.navigationController!,
configuration: config, completionHandler: { (provider: AWSSignInProvider, error: Error?) in
if error == nil {
//get parameters
}
} else {
print(error as Any)
}
})
}
Prerequisites:
App registered with MobileHub
Cognito Setup in MobileHub
Mobilehub integrated with Swift Project using AWS SDK
If you're like me, you did this with little to no difficulty and now you're stuck trying to get the username and other parameters from the logged in user. There are a lot of answers, but thus far, I haven't stumbled upon one that gets you all the way there.
I was able to piece this together from various sources:
func getUsername() {
//to check if user is logged in with Cognito... not sure if this is necessary
let identityManager = AWSIdentityManager.default()
let identityProvider = identityManager.credentialsProvider.identityProvider.identityProviderName
if identityProvider == "cognito-identity.amazonaws.com" {
print("************LOGGED IN WITH COGNITO************")
let serviceConfiguration = AWSServiceConfiguration(region: .USWest2, credentialsProvider: nil)
let userPoolConfiguration = AWSCognitoIdentityUserPoolConfiguration(clientId: "YourClientID", clientSecret: "YourSecretKey", poolId: "YourPoolID")
AWSCognitoIdentityUserPool.register(with: serviceConfiguration, userPoolConfiguration: userPoolConfiguration, forKey: "YourPoolName (typically formatted as YourAppName_userpoool_MOBILEHUB_12345678")
let pool = AWSCognitoIdentityUserPool(forKey: "YourPoolName")
// the following line doesn't seem to be necessary and isn't used so I've commented it out, but it is included in official documentation
// let credentialsProvider = AWSCognitoCredentialsProvider(regionType: .USWest2, identityPoolId: "YourPoolID", identityProviderManager:pool)
if let username = pool.currentUser()?.username {
print("Username Retrieved Successfully: \(username)")
} else {
print("Error getting username from current user - attempt to get user")
let user = pool.getUser()
let username = user.username
print("Username: \(username)")
}
}
}
To get your ClientID, Secret Key, and PoolID, check your awsconfiguration.json
To get your PoolName, login to MobileHub, and in your project's backend, go to User Sign in, click Email and Password, then click Edit in Cognito. The following page will have your Pool Name as "YourAppName_userpool_MOBILEHUB_12345678"
Edit: To get all of the attributes as well:
if let userFromPool = pool.currentUser() {
userFromPool.getDetails().continueOnSuccessWith(block: { (task) -> Any? in
DispatchQueue.main.async {
if let error = task.error as NSError? {
print("Error getting user attributes from Cognito: \(error)")
} else {
let response = task.result
if let userAttributes = response?.userAttributes {
print("user attributes found: \(userAttributes)")
for attribute in userAttributes {
if attribute.name == "email" {
if let email = attribute.value {
print("User Email: \(email)")
}
}
}
If you're using Cognito User Pools, you can use this:
import AWSUserPoolsSignIn
AWSCognitoUserPoolsSignInProvider.sharedInstance()
.getUserPool()
.currentUser()?
.username

Swift Firebase 4.0 - observeSingleEvent not returning data set (but authentication is working)

I have been working with Firebase on Android for the last 12 months+, with success. I just switched over to Swift and am attempting to read data from the same Firebase database I created and have been using the last 12 months+. Since there is security applied to the FB DB the first thing I did was to get FB authentication (from Swift) working. This works. Now, I am trying to get a simple observeSingleEvent operational and am struggling.
The Firebase DB is the same old stuff. It has a users node off of the root. For starters I would just like to read in a user from the user's node. I know authentication is working because when I submit my email and password I receive a confirmation. When the email / password are wrong I do not get confirmation. Given this validates my connection to the DB and as a test I stuck the following code in right after login validation.
When I debug this it simply skips from the "self.ref?.child("users").observeSingleEvent..." to the bracket below. i.e. It never acknowledges there is data available, but there is data available.
To avoid anyone asking "What do you need?" What I am looking for is an answer to why I receive no data result set with the code below given there is data in the FB DB and I have been reading/writing that data on Android for the last 12+ months.
Any/all help is welcome as I cut my teeth on Swift / FB 4.0
#IBAction func signInButtonTapped(_ sender: UIButton) {
// TODO: Do some form validation on the email and password
if let email = emailTextField.text, let pass = passwordTextField.text {
// Check if it's sign in or register
if isSignIn {
// Sign in the user with Firebase
Auth.auth().signIn(withEmail: email, password: pass, completion: { (user, error) in
// Check that user isn't nil
if let u = user {
// User is found, go to home screen
self.ref = Database.database().reference()
self.ref?.child("users").observeSingleEvent(of: .value, with: {( snapshot) in
let value = snapshot.value as? NSDictionary
let username = value?["username"] as? String ?? ""
print ("*** " + username)
})
}
else {
// Error: check error and show message
}
})
}
Since observeSingleEvent is an async call so it is running on the background thread, that is why it jumps on to the next bracket when you put a break point on self.ref, because it doesnt block the current thread of execution and does execute after sometime on background thread
One way to do is this:
#IBAction func signInButtonTapped(_ sender: UIButton) {
// TODO: Do some form validation on the email and password
if let email = emailTextField.text, let pass = passwordTextField.text {
// Check if it's sign in or register
if isSignIn {
// Sign in the user with Firebase
Auth.auth().signIn(withEmail: email, password: pass, completion: { (user, error) in
// Check that user isn't nil
if let u = user {
// User is found, go to home screen
self.fetchUserName { fetchedUserName in
print(fetchedUserName)
}
}
else {
// Error: check error and show message
}
})
}
func fetchUserName(completionHandler: #escaping (String) -> Void) {
self.ref = Database.database().reference()
self.ref?.child("users").observeSingleEvent(of: .value, with: {( snapshot) in
//let value = snapshot.value as? NSDictionary
if let value = snapshot.value as? [String: Any] {
print(value)
let username = value["username"] as? String ?? ""
print (username)
completionHandler(username)
}
})
}

How to check if user needs to re-authenticate using Firebase Authentication

I am using Firebase to log in users into my app, but when I am adding the capability to manage their account like changing their email, password and so on. The documentation says that if the user have not recently signed in they need to re-authenticate, but my question is: How can I check if the user have signed in recently or not? According to the docs the error will return FIRAuthErrorCodeCredentialTooOld, but how can I check this?
Swift 3
I had to do this yesterday when trying to delete a user. One thing to note is FIRAuthErrorCodeCredentialTooOld is now FIRAuthErrorCode.errorCodeRequiresRecentLogin
What I did was trigger a UIView to ask for log in details if that error is thrown. Since I was using email and password, that's what I collected from the user in my example.
private func deleteUser() {
//get the current user
guard let currentUser = FIRAuth.auth()?.currentUser else { return }
currentUser.delete { (error) in
if error == nil {
//currentUser is deleted
} else {
//this gets the error code
guard let errorCode = FIRAuthErrorCode(rawValue: error!._code) else { return }
if errorCode == FIRAuthErrorCode.errorCodeRequiresRecentLogin {
//create UIView to get user login information
let loginView = [yourLoginUIViewController]
self.present(loginView, animated: true, completion: nil)
}
}
}
Once I had the login information I ran this function to reauthenticate the user. In my case I ran it the loginView in the above code if the login in was successful:
func reauthenticateUserWith(email: String, password: String) {
FIRAuth.auth()?.signIn(withEmail: email, password: password) { (user, error) in
if error == nil {
//display UIView to delete user again
let deleteUserView = deleteUserView()
present(deleteUserView, animated: true, completion: nil)
} else {
//handle error
print(error!.localizedDescription)
}
}
}
The deleteUserView in my case calls deleteUser() on a button tap from the user. You can also use UIAlertController in place of the custom UIViews, but that's up to you.
Hope this helps.
Update for current Swift 5
let user = Auth.auth().currentUser
user?.delete { error in
if let error = error {
let authErr = AuthErrorCode(rawValue: error.code)
if authErr == .requiresRecentLogin {
// reauthenticate
}
// other error
} else {
// delete success
}
}
According to the documents, there is currently no way to check FIRAuthErrorCodeCredentialTooOld other than going through the deleting of the account or the other sensitive cases mentioned.
If you are like me and ended up here because you are trying to figure out how to handle removing someone from Auth and removing other user data in Cloud Firestore, Realtime Database, and/or Cloud Storage, then there is a better solution.
Check out the Delete User Data Extension from Firebase to handle this. In short, when a user profile is deleted from Auth, you can use this also to delete data associated with the uid from those other Firebase data storage tools.