Answer a question

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?

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

Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐