Firebase authentication: linking multiple accounts in Swift - 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."

Related

IOS Firebase. User UID changing after restarting the application

If i understood correct the user UID its this is a unique uid, until the user logs out. I mean he can close/open the app many times and user UID must be the same.
I have test class:
class UserFirebase {
func authorization(completionHandler: #escaping (Result<AuthDataResult?, Error>) -> Void) {
Auth.auth().signInAnonymously { authResult, error in
if error == nil {
completionHandler(.success(authResult))
return
}
completionHandler(.failure(error))
}
}
func singOut() {
try? Auth.auth().signOut()
}
func getUserUUID() -> String? {
return Auth.auth().currentUser?.uid
}
func isAuthorized() -> Bool {
return Auth.auth().currentUser != nil
}
}
when app is running i using this class like this:
let userFirebaseManager: UserFirebase = UserFirebase()
if userFirebaseManager.isAuthorized() {
// make something
} else {
userFirebaseManager.authorization(completionHandler: {[weak self] (result) in
// make something
})
}
every time I start the app, the user isAuthorized() == false. Shouldn't it persist until I press logout?
UPD:
why does my currentUser.uid change every time I restart the application?
The UID of an anonymous user is deleted when the user signs out. It cannot be regained after that, not even when you sign in on the same device.
Also see:
How constant is the Firebase Anonymous ID
Firebase Anonymous Authentication
Firebase Anonymous Auth: Restore account
How to logout and then re authenticate an anonymous firebase user
Anonymous users are signed out once the app is closed. I'm not sure why you need to sign in anonymously AND keep that UUID known. If you need to sign in anonymously just to securely access your Firebase project, it shouldn't matter if the user gets signed out. If you want to preserve the UUID, the user needs to create an account with Auth.auth().createUser(withEmail: String, password: String, completion: ((AuthDataResult?, Error?) -> Void)

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

Microsoft Azure mobile SDK custom provider login IOS

I have followed this tutorial to implement a login with custom provider on an Azure mobile app. The backend works perfectly but when I try to login to my new custom controller I'm not able to do it. It's possible to implement it with Xamarin and also with java Android but is no way to do it with Objective C or Swift.
The object MSClient on Microsoft Azure mobile SDK only has two login implementations.
I have tried both but without luck, the callback always returns an empty client.
I also have tried to store the token created by own API use it for login call but without luck again.
Here is my Swift code:
let client = MSClient(applicationURLString: "https://myApp.azurewebsites.net")
client.login(withProvider: "custom", urlScheme: "myApp", parameters: ["username": "pau", "password": "123456"], controller: self, animated: true) {user, error in
print("USER", user)
print("ERROR", error)
}
We found a solution, it's really easy but the msclient documentation is not clear enough. You just need to pass whatever you need (i.e: username,password) as dictionary in token parameter.
Client.msClient.login(withProvider: "auth", token: params, completion: {user, error in
print("USER", user)
print("ERROR", error)
print("USER ID", user?.userId)
print("TOKEN", user?.mobileServiceAuthenticationToken)
if let user: MSUser = user {
guard let username: String = user.userId else { return }
guard let token: String = user.mobileServiceAuthenticationToken else { return }
Client.username = username
Client.msClient.currentUser = user
completion(true)
}else {
completion(false)
}
})

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.