respect the session expiration on all pages

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 :pray:t3::pray:t3::pray:t3::pray:t3:

Help me please ;( or tell me how I can do to achieve

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 :pray::pray::pray::pray:

@riveraanuar22

Damn all my written text is just gone (i hate that)!
I will reply here later when i am at home.

In the meanwhile, try to figure out what is exactly the difference between …

  1. normal/standard-page-code
  2. master-page-code
  3. public-file-js-code
    ?

@russian-dima ok i take care of that

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!

@russian-dima So from what I understand, it is only to introduce the my code from above in the js file to make it public?