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
You should use Timeoutable model trait.
Timeoutable takes care of veryfing whether a user session has already expired or not. When a session expires after the configured time, the user will be asked for credentials again, it means, he/she will be redirected to the sign in page.
Options
Timeoutable adds the following options to devise_for:
- +timeout_in+: the interval to timeout the user session without activity.
In your model you need
devise :timeoutable
# along with :database_authenticatable, :registerable and other things.
Also, take a look at config/initializers/devise.rb
, you can configure timeout value there.
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.
I know this question has already been answered, but I thought I would provide my solution as well, since in my case I was looking for more functionality than even Devise's timeoutable feature could provide. A big thanks to @Sergio Tulentsev for providing me with helpful explanations and ideas in the comments section of his answer!
Because Devise runs on the server side and not the client side, when the authentication token times out, the client is not aware of the timeout until the user performs an action that calls a Rails controller. This means that the user is not redirected to the login page on timeout until they perform an action that calls a Rails controller.
In my case, this was a problem because my web page contained user-sensitive information that I did not want displayed indefinitely if the user forgot to logout and no action was performed on the page.
I installed the gem auto-session-timeout, which adds code to the client side to periodically check if the authentication token has expired.
It doesn't say in the ReadMe, but auto-session-timeout requires jquery-periodicalupdater in order to work. This page contains the reason why:
Here are the steps I took in order to get auto-session-timeout to work with Devise:
First of all, I followed the steps here in order to customize the Devise sessions controllers. Just for reference, my config/routes.rb file is set up in the following way:
Myapp::Application.routes.draw do
devise_for :users, controllers: { sessions: "users/sessions" }
#other routes
end
In app/controllers/users/sessions_controller.rb, I have the following code:
class Users::SessionsController < Devise::SessionsController
layout 'login' #specifies that the template app/views/layouts/login.html.erb should be used instead of app/views/layouts/application.html.erb for the login page
#configure auto_session_timeout
def active
render_session_status
end
def timeout
flash[:notice] = "Your session has timed out."
redirect_to "/users/sign_in"
end
end
In app/controllers/application_controller.rb, I have the following code:
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :authenticate_user!
auto_session_timeout 30.minutes
end
Note that we set the authentication token expiration time to be 30 minutes using auto_session_timeout. This replaces the Devise timeoutable functionality.
In my app, I have two layout templates - one for the all the pages that the user sees when they are logged in (app/views/layouts/application.html.erb), and one just for the login screen (app/views/layouts/login.html.erb). In both of these files, I added the line below within the html <body>
element:
<%= auto_session_timeout_js %>
This code will generate Javascript that checks the status of the authentication token every 60 seconds (this time interval is configurable). If the token has timed out, the Javascript code will call the timeout
method in the app/controllers/users/sessions_controller.rb file.
Note that I have included this code on the app/views/layouts/login.html.erb page. The reason for this is because if there is no activity on the login page for more than 30 minutes (or whatever the auto_session_timeout
setting is in the application_controller.rb file), then the authentication token will expire, and the user will receive an Invalid Authentication Token error when trying to login. Adding the code <%= auto_session_timeout_js %>
will cause the login to be refreshed when the authentication token expires, thus preventing this error from occurring.
Using Devise Gem:
We can use inbuilt feature of the devise gem but it will not automatically redirect to the sign in page after timeout, redirection will be done after we perform any action.
We can Perform automatically sign out:
By using gem "auto-session-timeout"
https://github.com/pelargir/auto-session-timeout
The disadvantage of using this gem is that it will logout automatically if user is only typing(performing key press event) till the timeout time.
we can override the disadvantage by using Javascript:
Step 1: Define the routes
get 'application/session_time'
Step 2: JavaScript will contain
$(document).ready(function(){
if($("#user_logged").is(":visible") == true )
{
$(document).on( "keypress keydown", function () {
console.log("hello");
$.ajax({
type:"GET",
url:"/application/session_time",
dataType:"html",
});
});
}
});
Step 3: application controller will contain:
@session_time = 5.minute
auto_session_timeout @session_time
def session_time
@session_time = 5.minute
end
Step 4: div to find it is sign in page or not
<% if user_signed_in? %>
<div id="user_logged"></div>
<% end %>
The blank div is kept because we have to load JavaScript only when user is logged in ,so instead of finding current user is nil or not.
I have done with the blank div,it will be available if user is loggedin,so in beginning of JavaScript it is checked that div_id "user_loged" is present or not.