Home > Back-end >  Check if user isLoggedIn MongoDB Realm Web SDK
Check if user isLoggedIn MongoDB Realm Web SDK

Time:01-23

I wish to check if a user is already logged in through email/password auth via mongodb realm web-sdk. Knowing if the user is logged in will allow me to hide the loggin page from site and instead show a log out button.

So far I've successfully created a user and logged in. Using the code/methods below.

    async function registerEmailPassword(email, password) {
        try {
            const user = await app.emailPasswordAuth.registerUser({ email, password });
            return user;
        } catch (error) {
            console.error("Failed to register", error)
        }
    }

    async function loginEmailPassword(email, password) {
        // Create an email/password credential
        const credentials = Realm.Credentials.emailPassword(email, password);
        try {
          // Authenticate the user
          const user = await app.logIn(credentials);
          // `App.currentUser` updates to match the logged in user
          console.assert(user.id === app.currentUser.id);
          return user;
        } catch (error) {
          console.error("Failed to log in", error);
        }
      }

CodePudding user response:

While going through the mongodb class documentation, I wrote the following function which appears to work.

The code is checking for if their is any user in currentUser, if their is no currentUser, their no account logged in. In the event their is a currentUser, the code then checks using currentUser.isLoggedIn if that user is logged and at the end returns a boolean value.

    async function isUserLoggedIn() {
        try {
            const userStatus = await app.currentUser;
            if (userStatus == null) {
                return false
            } else {
                const userStatus = await app.currentUser.isLoggedIn;
                return userStatus
            }
        } catch (error) {
            console.log("Failed to fetch user", error);
        }
    }

    // Check if user is logged in
    isUserLoggedIn().then((value) => {
        console.log(value);
    }).catch((error) => {
        console.log(error);
    });
  • Related