Good afternoon I have a question I hope you can help me, I have a login which directs to a page And which has a timer that after a certain time the session expires and shows the login again I show code
import wixStorage from 'wix-storage';
import wixLocation from 'wix-location';
import wixData from 'wix-data';
import wixWindow from 'wix-window';
var onlineState
$w.onReady(() => {
setInterval(logOut, (1*1000*60)); // --> LOGOUT every 5min
$w("#button1").onClick(async () => {
//getting online-status...
//onlineState = wixStorage.session.getItem("onlineState");
if(onlineState === "true") {
wixLocation.to("/eventos")
}
else {
let email = $w("#email").value
let contrasena = $w("#contrasena").value
await checkLogin(email, contrasena)
}
})
})
function logOut() {onlineState === "true";
//setting online-status...
wixStorage.session.setItem("onlineState", "false");
wixWindow.openLightbox('login expired');
}
async function checkLogin(email, contrasena) {
wixData.query("logingers")
.eq("title", email)
.eq("contrasena", contrasena)
.find()
.then((res)=>{
if (res.items.length > 0) {//setting online-status...
wixStorage.session.setItem("onlineState", "true");
wixLocation.to("/eventos")
} else {
wixWindow.openLightbox('loginwarn');
//console.error("Email/Contrasena wrong!")
}
});
}
that works perfectly as long as I stay on the page where the login is located, if I browse the site the time set for the session to expire it is not respected, what I am looking for this time is the way in which it respects the time even being on other pages
I need your help please help me
To get your functionality to work, you will need to place your code onto a public JS-File and not on the page itself. Or you do it on the MASTER-PAGE, but doing it on MASTER-PAGE, it would expect that you have your header on every of your pages.
To get more info about the functionality you are trying to achieve, you will find here…
I’ve already been reading it but I don’t understand how to achieve it :(, would you be so kind and gentle to explain step by step how to achieve it I am a beginner in this aspect please help me
Ok, as i can see you are realy interested on this feature to be integrated on your site. You have surely also already inspected my example as most as possible, by viewing all given console-logs in my interactive-example.
import { validateSession, set_newTimestamp } from 'public/events.js';
//------User-Interface-----------------
var OnlineCheckClocking = 10; //(sec)
//------User-Interface-----------------
$w.onReady(() => {set_newTimestamp();
let myInterval = setInterval(validateSession, OnlineCheckClocking*1000);
$w('#button1').onClick(()=>{set_newTimestamp();});
})
EVENT-Page-CODE:
import { session } from 'wix-storage';
//------User-Interface-------------------------
var maxOnlineTime = 0.5; //0,5-Minutes --> 30-secs! --> Logging-Out ater 30-secs
//------User-Interface-------------------------
//var DATA; <<<<<----------THAT WAS THE PROBLEM ! ! !
export function set_newTimestamp() {
let lastActionStamp=new Date();
let expirationDate =
new Date(lastActionStamp.getTime() + 1000 * 60*maxOnlineTime);
let DATA={};
DATA.maxOnlineTime = maxOnlineTime;
DATA.expiration = expirationDate.getTime();
session.setItem("session", JSON.stringify(DATA)); <<<<<-THAT WAS THE SOLUTION ! ! !
}
export async function validateSession() {let message;
let DATA = await JSON.parse(session.getItem('session'));
let onlineTime = Number(new Date())-Number(DATA.expiration);
DATA.onlineTime = onlineTime;
if (new Date()>=DATA.expiration) {
message = {
onlineTime: DATA.onlineTime,
expiration: DATA.expiration,
type:'success', action:'log-out',
msg: 'Your online-time is expired ---> time for Log-Out!!!'
}
}
else {
message = {
onlineTime: DATA.onlineTime,
expiration: DATA.expiration,
type:'success', action:'renew',
msg: 'You are lucky, your time has not expired yet --> you can stay!'
}
}
}
You can store the token in the session storage, and update it every while, before updating, check if the token is expired, either by checking its creation time or by checking against a DB of tokens (more secure).
Note: You should only set the interval in the code in the masterPage.js file.
// Public: functions.jsimport { session } from 'wix-storage';import users from 'wix-users';const token_lifetime = 20 * 1000 * 60; // 20 minexport function renewToken() {const obj = {
token = Math.floor(Math.random() * 10000000000000000000000000),
expiration: new Date(new Date().getTime() + token_lifetime)}
session.setItem(JSON.stringify(obj))}export function validateSession() {const data = session.getItem('session');if (typeof data === 'string') {const obj = JSON.parse(data);if (new Date().getTime() >= obj.expiration_time) {// Log the user out.
users.logout();}} else {renewToken();}}
This way, you won’t need to worry about clearing the interval as it only validates the current token, but you still need to renew the token by calling the renew( ) function.
If the token doesn’t get renewed within 20 min, the user will be automatically kicked out of the website (logged out).
Note #1: If you want a secure (reliable way) to achieve the same, create a function on the backend to retrieve the token from the DB, and check if it’s still valid or not, and return the appropriate response to the frontend.
(of course i do not want to show my own FULL-CODE).
But in general you already have to most important parts of it (take a look above!)
And now it’s on you to understand all that code!
Good luck!
If you are still not able to make this work → than your coding skills did not reach the needed level yet → try to improve your coding skills first (or study the whole post for weeks → until you understand it) → this is the only way to understand all that shi…