Lazybob
Lazybob

Reputation: 294

How to handle inactive users and log them out in react JavaScript?

I'm working on a private site with important data, and I want to log out any user who hasn't done anything for 10min (forgot the tab open in the background as an example). How can I do that, is just running an event listener to the mouse clicks with a timer is fine, or are there other better solutions for this?

Upvotes: 1

Views: 4553

Answers (2)

Sankshit Pandoh
Sankshit Pandoh

Reputation: 79

event listeners for mouse movement (not clicks), and event listeners for keyboard clicks as well should do the job.

Let's say you want to log out the user after 10mins of inactivity. Simply start a timer (for 10mins) the moment user logs in, every time the user makes any mouse movement or any keyboard clicks, use the event listener to reset the timer. If there is no activity, after 10mins, the timer should execute log out functionality.

Update :

Like the case suggested by Vishnu Bhadoriya, in that case, the idle solution should be to implement a heartbeat b/w the client and the server. Now, in this case, your mouse and keyboard listeners would send a lifeline event to the server, and the server will keep its session alive. When the lifeline event is not received by the server for more than 10mins (threshold for activity), the server can emit an event to the client which can log him out or can simple invalidate the client's auth token

Upvotes: 2

Vishnu Bhadoriya
Vishnu Bhadoriya

Reputation: 1676

This can be achieved by JavaScript only. Since our web app can be open in multiple tab, so its better to store last activity of user in localStorage

First lets declare events which we consider as user activity and store time of user activity in localStorage

document.addEventListener("mousemove", () =>{ 
  localStorage.setItem('lastActvity', new Date())
});
document.addEventListener("click", () =>{ 
  localStorage.setItem('lastActvity', new Date())
});

Next lets create interval which will be checked on every given interval.

let timeInterval = setInterval(() => {
  let lastAcivity = localStorage.getItem('lastActvity')
  var diffMs = Math.abs(new Date(lastAcivity) - new Date()); // milliseconds between now & last activity
  var seconds = Math.floor((diffMs/1000));
  var minute = Math.floor((seconds/60));
  console.log(seconds +' sec and '+minute+' min since last activity')
  if(minute == 10){
    console.log('No activity from last 10 minutes... Logging Out')
    clearInterval(timeInterval)
    //code for logout or anything...
  }

},1000)

Upvotes: 5

Related Questions