Check whether a user is logged in GET or POST response

Hello, I am trying to figure out how to check whether a user is logged in either through backend code or a database-based solution. Said another way, I would like a way for the backend to check whether a given user is logged in when responding to a GET or POST.

Full Situation

  1. In a Custom Tool in Tracking & Analytics, I retrieve a variable from another site (foxySID)
  2. In another Custom Tool, I make a POST request to the post_foxy_session function (shown below)

post_foxy_session(request)

  1. Define options for response debugging
  2. Query “Visitors” table to find the most recent visitor
  3. Section in question
  4. Query “Discounts” table with results from “Visitors” table query to find a matching user record
  5. Log foxySID (body of the request) to the returned row of the “Discounts table”

Section in question
I would like to check whether the user that is identified as the most recent visitor is currently logged in. If they are currently logged in, proceed with steps 4 and 5. If the user is not currently logged in, I want to abort the process.

The code I’ve written for this section does not work, but it may give you an idea as to what I am trying to accomplish. Said more simply, I would like a way for the backend to check whether a given user is logged in when responding to a GET or POST.

export function post_foxy_session(request) {
    let options = {
        "headers": {
            "Content-Type": "application/json",
            "Referrer-Policy" : "same-origin"
        }
    };
    return request.body.text()
        .then((body) => {
            let foxySID = body;
            options.body = {
                "session" : foxySID
            }

            return wixData.query("Visitors")
                .descending("_updatedDate")
                .find()
                .then((res) => {
                    var userId = res.items[0].userId;

                    /* Section in question -------------
                    //only proceed if the user is logged in
                    var user = wixUsers.getUser(userId)
                    
                    if (!user.loggedIn) {
                        options.body = {
                            "session" : "User is not logged in"
                        }
                        return ok(options);
                    }
                    Section in question ----------------- */ 
                    
                    return wixData.query("Discounts")
                        .eq("memberId", userId)
                        .find()
                        .then((results) => {
                            if (results.items.length > 0) {
                                var toUpdate = results.items[0]
                                toUpdate.foxySID = foxySID;
                                return wixData.update("Discounts", toUpdate)
                                .then((output) => {
                                    return ok(options);
                                })
                            }
                            else {
                                options.body = {
                                    "session" : "current user is not a member"
                                }
                                return ok(options);
                            }
                        })
                })
        });
}

Any guidance on this would be much appreciated!

Steve

You can have a database which you can ping every 15 seconds (more or less as you see productive) by a user who is logged in. A sample page code can be like below:

$w.onReady(function () {
   setInterval( () => {
      if(wixUsers.currentUser.loggedIn === true) {
         fire();
      }
   }, 15000);
});

function fire() {
   wixData.query('database')
   .limit(1)
   .find()
   .then( (results) => {
      let Item = results.items[0]
      let date = Math.floor(Date.now() / 1000); //current time
      Item.unixUpdated = Number(date); //update time in database
      wixData.update('database', Item);
   });
}

Now you can check via your backend code if the last update to the first (and only) item in the database was more than 60 seconds or not. If it was more than 60 seconds it would mean no user is currently on your site (logged in). Setting thresholds (60 seconds) to consider user being logged in or not is up to you.

Sample backend code:

function checkForUser() {
   wixData.query('database')    
   .limit(1)    
   .find()    
   .then( (results) => {       
      let Item = results.items[0]       
      let lastUpdated = Number(Item.unixUpdated);
      let current = Math.floor(Date.now() / 1000);
      let diff = current - lastUpdated;
      if(diff > 60) {
        //no one here
      } else {
        //we've got company
      }
   });
}

This is one way of doing it.

Thank you for the reply!

What I am looking for is a function that will take a userId and return true if that user is logged in, or false if that user is not logged in. Not in the front-end (ie, the user checks if they themselves are logged in), but in the backend. I want to be able to GET/POST request a userId and see if the user is logged in.

This really helped my with a custom login screen thankyou you guys are amazing.

Any updates about this?