auto-session-timeout: automatic session timeouts for Rails
We’ve just released auto-session-timeout, a Ruby gem that automatically times out idle sessions in your Rails application.
Have you ever wanted to force users off your app when they go idle for a certain period of time? Many online banking sites do this. If your app is used on any kind of public or shared computer, it’s a necessity: the next person to sit down shouldn’t find the previous user still logged in.
How it works
Tell your application controller how long a session can sit idle:
class ApplicationController < ActionController::Base
auto_session_timeout 1.hour
end
Every request resets the clock, except the gem’s own background status checks, so an open browser tab doesn’t keep a session alive forever. Once a session goes longer than the timeout without a request, it’s reset on the server.
That handles the server side, but what about a user who walks away with the page still open in their browser? For that, add the JavaScript helper to your layout, inside the <body> tag. Only render it when someone is logged in:
<% if logged_in? -%>
<%= auto_session_timeout_js %>
<% end -%>
The helper quietly checks with the server every 60 seconds. When the session has expired, it sends the browser to your timeout page, so the screen doesn’t keep showing private information to whoever walks up next. Want it to check more often? Pass a frequency in seconds:
<%= auto_session_timeout_js :frequency => 15 %>
The gem also includes default actions for checking the session status and handling the timeout. Add them to your sessions controller:
class SessionsController < ApplicationController
auto_session_timeout_actions
end
Then map them in routes.rb:
map.active '/active', :controller => 'sessions', :action => 'active'
map.timeout '/timeout', :controller => 'sessions', :action => 'timeout'
The default timeout action shows a “Your session has timed out” message and sends the user back to the login page. To customize either action, override it in your controller and call render_session_status or render_session_timeout to fall back on the built-in behavior.
Installation
Install the gem:
gem install auto-session-timeout
Or install it as a plugin in your Rails project:
script/plugin install git://github.com/pelargir/auto-session-timeout.git
Check out the README for the full details.
Contributions welcome
The project is open source on GitHub under the MIT license. If you run into a bug or have an idea for an improvement, please open an issue. Even better, fork the project and send us a pull request. We’d love to see what you come up with.
Update: auto-session-timeout is still actively maintained and now supports current versions of Rails, including Rails 8. Installation and configuration have changed since this post was written, so see the README on GitHub for up-to-date instructions.