respect the session expiration on all pages

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.

Ok to make it as short as possible, we will look onto the end-Solutions, given in this post …

One of myself…

GENERAL-Page-CODE:

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!'
    }
  }  
}

And one of Ahmads-Version!

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.


// masterPage.jsimport { validateSession } from 'public/functions.js';const interval_duration = 5 * 1000; // 5 sec

$w.onReady(() => {setInterval(validateSession, interval_duration)})
// 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.

// Backend: sessions.jswimport { query } from 'wix-data';import { currentUser } from 'wix-users-backend';export function validateSession(token) {return query('tokens').eq('_owner', currentUser.id).eq('token', token).limit(1).find({ suppressAuth: true }).then(x => {if (x.length > 0) {const item = x.items[0];if (new Date().getTime() >= item.expiration_time) {return { type: 'success', action: 'logout' }} else {return { type: 'success', action: 'renew' }}} else {return { type: 'success', action: 'renew' }}})}

Note #2: If you want to validate the token on the backend, you should consider the time zone offset on the browser as servers use UTC time instead.

Normaly this is all you have to know, to reconstruct the integrated feature on my site…

I think your biggest problem will be that you know anything about → PUBLIC-JS-FILE ?

So here it is…

  1. Create first a public-js-file (in my case it is called vnAnalytics) you can call it like you want!

Place your code on the new created Public-JS-File…


(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! :wink:

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…:laughing:

And → NEVER-GIVE-UP!