Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 586
e.iluf Avatar asked Aug 08 '20 15:08

e.iluf


People also ask

Can I use MongoDB realm sync with a mobile app?

This article targets developers looking to build the Realm mobile database into their mobile apps and (optionally) use MongoDB Realm Sync. It focuses on the data architecture, both the schema and the partitioning strategy. I use a chat app as an example, but you can apply the same principals to any mobile app.

How to open a synced realm in Swift?

// Get a configuration to open the synced realm. // opening the local copy. // Go to the list of projects in the user object contained in the user realm. Open the ProjectsViewController.swift file, which is where we present the user with a list of projects they are a member of.

How to manage members of a user's project in Swift?

Part 2: Manage members of a user's project. Navigate to the Models.swift file to implement the Realm Object Models used in this app. Realm object models derive from Object from the RealmSwift library, which allows us to store them in Realm Database. The Task class is currently just a normal Swift class.

How do I log out of the welcomeviewcontroller in Swift?

Open the ProjectsViewController.swift file, which is where we present the user with a list of projects they are a member of. Let's provide a way for a user to log out and get back to the WelcomeViewController. The viewDidLoad () method hooks up the Log Out button at the top of the view to the logOutButtonDidClick () method.


1 Answers

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

like image 59
Jay Avatar answered Oct 25 '22 06:10

Jay