How to set up in the rails application that if any user is idle for 30 minutes or a specific period of time he should be automatically get logged out. Can any one give any s
There's a simple way of dealing with this that hasn't been mentioned which requires no extra gems or dependencies.
Say in initializers/devise.rb you've set config.timeout_in = 30.minutes and added :timeoutable to your model. Trigger the following javascript on page loads when a user is logged in:
setAccurateTimeout(() => {
window.location.reload();
}, 30 * 60 * 1000); // minutes (from devise setting) * sec * ms
function setAccurateTimeout(callback, length) {
// adjust any discrepencies every 5s
let speed = 5000,
steps = length / speed,
count = 0,
start = new Date().getTime();
function instance() {
if (count++ == steps) {
callback();
} else {
// console.log(`step ${count} of ${steps}, time passed ${count * speed}ms of ${length}ms`)
let diff = (new Date().getTime() - start) - (count * speed);
// console.log(`accuracy diff ${diff}ms, adjusted interval: ${speed - diff}ms`);
window.setTimeout(instance, (speed - diff));
}
}
window.setTimeout(instance, speed);
}
A regular setTimeout could probably be used, even though over time it introduces inaccuracies due to CPU usage. It would likely just trigger the logout reload slightly later than intended.
The server will terminate the session slightly before this finishes due to being initialized prior to javascript on the client side. When the page reloads the browser will end up on the login screen. This method also makes it easy to trigger a warning modal in advance, for example at the 2 minute mark with a countdown showing the remaining seconds and a button which can be clicked to stay signed in.
Extra tip: on a "stay signed in" button, set the url to one of your pages and add the data-remote='true' attribute. When clicked this will fire off a request to the server without reloading the page the user is on, thus fulfilling the activity requirement and resetting devise's timeout without needing to reload or navigate anywhere. Cancel any programmatic page reload, then restart the main timeout.