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
- In a Custom Tool in Tracking & Analytics, I retrieve a variable from another site (foxySID)
- In another Custom Tool, I make a POST request to the post_foxy_session function (shown below)
post_foxy_session(request)
- Define options for response debugging
- Query “Visitors” table to find the most recent visitor
- Section in question
- Query “Discounts” table with results from “Visitors” table query to find a matching user record
- 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