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

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.

Related

How to handle user after registration?

I need to register my user's with both phone authentication and email authentication. I have successfully done both. However, with the way I've structured my code, it's a bit flimsy.
After a user registers with their phone number, they are automatically signed in. But before they gain access to the application I need them to register with their email as well but I can't do so until they are signed in with their phone.
Group {
if (self.session.session != nil) {
if user?.metadata.creationDate != user?.metadata.lastSignInDate {
AppView()
} else {
EmailRegisterView()
}
} else {
OnBoardingView()
}
}.onAppear(perform: {
session.listen()
})
With the code I have, if the user for some reason logs out of their account on the same day that they've created it, they will be taken to the EmailRegisterView() again which will cause problems.
Is there another way to redirect users to the EmailRegisterView() only if they are new users, and once they have finished there, send them to the AppView()?
Here is my code for the phone authentication...
func phoneRegister () {
let credential = PhoneAuthProvider.provider().credential(withVerificationID: self.verificationCode, verificationCode: self.code)
Auth.auth().signIn(with: credential) { (result, error) in
if error != nil{
self.alertMessage = (error?.localizedDescription)!
self.alert.toggle()
return
}
UserDefaults.standard.set(true, forKey: "status")
NotificationCenter.default.post(name: NSNotification.Name("statusChange"), object: nil)
}
}
Looks like you can add a key to user default and check the value every time the user open the app.
If the userdefault bool key, let's say IsUserRegistered, doesn't exist or is set to false, then you navigate to login page/register page and set the key to true. Otherwise, if the the key is set to true, you just display the home view.

swift: How to keep ios user logged in using mongoDB Realm database and authentication

I want to keep user logged and not need to show login form everytime they open the app. I am using MongoDB Realm for database and authentication.
Right now the login works fine but it's required everytime the app is opened.
this my login code
#objc func signUp() {
setLoading(true);
app.usernamePasswordProviderClient().registerEmail(username!, password: password!, completion: {[weak self](error) in
// Completion handlers are not necessarily called on the UI thread.
// This call to DispatchQueue.main.sync ensures that any changes to the UI,
// namely disabling the loading indicator and navigating to the next page,
// are handled on the UI thread:
DispatchQueue.main.sync {
self!.setLoading(false);
guard error == nil else {
print("Signup failed: \(error!)")
self!.errorLabel.text = "Signup failed: \(error!.localizedDescription)"
return
}
print("Signup successful!")
// Registering just registers. Now we need to sign in, but we can reuse the existing username and password.
self!.errorLabel.text = "Signup successful! Signing in..."
self!.signIn()
}
})
}
#objc func signIn() {
print("Log in as user: \(username!)");
setLoading(true);
app.login(withCredential: AppCredentials(username: username!, password: password!)) { [weak self](maybeUser, error) in
DispatchQueue.main.sync {
self!.setLoading(false);
guard error == nil else {
// Auth error: user already exists? Try logging in as that user.
print("Login failed: \(error!)");
self!.errorLabel.text = "Login failed: \(error!.localizedDescription)"
return
}
guard let user = maybeUser else {
fatalError("Invalid user object?")
}
print("Login succeeded!");
self?.navigationController?.pushViewController(hostingController, animated: true)
}
this is my app rootView where I want to check and keep the user logged in
struct AppRootView: View {
var body: some View {
AnyView {
// check if user has already logged in here and then route them accordingly
if auth.token != nil {
homeMainView()
} else {
LoginController()
}
}
}
}
how can I keep user login with MongoDB realm?
From what I understand*, once a user authenticates, they will stay authenticated 'logged in' on that device until they are manually logged out, keeping in mind that once they are logged out their access token remains active for 30 minutes.
Two things from the guide
The access token for a session expires after thirty minutes. However,
a new session can be started by retrieving a new access token from
MongoDB Realm using the refresh token. (Important ->) The SDKs automatically take
care of refreshing access tokens, so you do not need to worry about
this when implementing client applications.
and
MongoDB Realm handles the access tokens and refresh tokens that
comprise a user session automatically.
What we are doing, which appears to be working ok, is this: When the app opens, we call a func handleSignIn which checks to see if the app has a .currentUser. If so, then we configure Realm. If not, a login/signup view is presented. Here's a snippit
func handleSignIn() {
if let _ = gTaskApp.currentUser() {
print("user is logged in")
self.configRealmSync()
} else {
print("not logged in; present sign in/signup view")
with gTaskApp being a global reference to our app
let gTaskApp = RealmApp(id: Constants.REALM_APP_ID)
*This is a work in progress so please feel free to correct me

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.

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

Firebase authentication: linking multiple accounts in Swift

I've set up Firebase authentication for my iOS app using Facebook, Google & email/password sign in and it's all working fine. This authentication only happens when the user wants to access high-priority parts of my app (i.e. I don't require users to sign in to start using the app).
On app start up, I sign users in anonymously in the background and that's working fine too.
I've read the documentation but I'm struggling to understand the code required to enable me to link an anonymous account to a Facebook/email signed in account in the following flow:
new user opens app
user signed in anonymously in the background (new user.uid "A" created)
low priority data stored against anonymous user in Firebase realtime DB
user hits a high-priority area so needs to authenticate
user signs in using Facebook (new user.uid "B" created)
previous user.uid "A" needs to be linked to user.uid "B"
My method currently looks like this:
func signupWithFacebook(){
// track the anonymous user to link later
let prevUser = FIRAuth.auth()?.currentUser
FBSDKLoginManager().logInWithReadPermissions(["public_profile", "email"], fromViewController: self) { (result, error) in
if let token = result?.token?.tokenString {
let credential = FIRFacebookAuthProvider.credentialWithAccessToken(token)
FIRAuth.auth()?.signInWithCredential(credential, completion: { (user, error) in
if user != nil && error == nil {
// Success
self.success?(user: user!)
dispatch_async(dispatch_get_main_queue(), {
self.dismissViewControllerAnimated(true, completion: nil)
})
}
})
}
}
}
Any pointers to remove the confusion would be great.
UPDATE:
I've realised I was confused about the app logic because of users being created during testing. Instead of 2 separate users being created for the above scenario (one authenticated via Facebook and another anonymously), all that happens is that the original anonymous user.uid "A" is "linked" to some Facebook authentication credentials. In the Firebase console this is shown by the anonymous uid changing from anonymous to one with the Facebook logo next to it.
This is what my working method looks like:
func signupWithFacebook(){
FBSDKLoginManager().logInWithReadPermissions(["public_profile", "email"], fromViewController: self) { (result, error) in
if let token = result?.token?.tokenString {
let credential = FIRFacebookAuthProvider.credentialWithAccessToken(token)
FIRAuth.auth()?.currentUser!.linkWithCredential(credential) { (user, error) in
if user != nil && error == nil {
// Success
self.success?(user: user!)
dispatch_async(dispatch_get_main_queue(), {
self.dismissViewControllerAnimated(true, completion: nil)
})
} else {
print("linkWithCredential error:", error)
}
}
}
}
}
So your code follows the first 2 steps in this link. But the documentation explicity says not to call signInWithCredential but instead call
FIRAuth.auth()?.currentUser.linkWithCredential(credential) { (user, error) in
// ...
}
After getting your credential from Facebook's SDK.
Quote from link: "If the call to linkWithCredential:completion: succeeds, the user's new account can access the anonymous account's Firebase data."