1. Skip to navigation
  2. Skip to content

The ELC Community Blog

A knowledge exchange on Ruby on Rails and Agile Development


Sliding Session Timeout plugin

by jeff on October 29, 2007

ELC Plugins

By default, sessions in Rails expire at a fixed time from the moment they are created. The Sliding Session Timeout plugin lets you configure your sessions to expire in a sliding window, a fixed time from the last page view.

To use it, place a call in your controller (typically application.rb) with the number of seconds in which to time out the session:

class ApplicationController < ActionController::Base
  sliding_session_timeout 3600
end

You can use Rails' built-in number helpers to make it more readable:

class ApplicationController < ActionController::Base
  sliding_session_timeout 60.minutes
end

You can also pass an optional method to be called upon session timeout:

class ApplicationController < ActionController::Base
  sliding_session_timeout 60.minutes, :on_expiration

  def on_expiration
    # do stuff...
  end
end
The plugin is available here: https://wush.net/svn/public/sliding_session_timeout

Feedback is welcome!

Updates:

Mandaryn asks: "Do you know how to force a redirect to a normal action from ajax call?"

By default, sliding_session_timeout will just call reset_session when your session times out. If you have a filter e.g. login_required to enforce that users are logged in, I've found this is one place you can handle the different types of requests rather than in an :on_expiration callback. The problem with adding render or redirect_to in an :on_expiration callback is that if any of your other filters (such as login_required) perform a render or redirect, you'll get a DoubleRenderError. So until I discover a nice way around that, I handle request formats something like so:

  before_filter :login_required
  sliding_session_timeout 10
  
  def login_required
    respond_to do |format|
      format.html { (redirect_to(login_url) and return false) }
      format.js do
        render :update do |p|
          p << "location.href = '#{login_url}';"
        end and return false
      end
    end unless session[:logged_in]
  end 

Comments

Mandaryn at 5:55 PM on November 5 2007

I have a problem with your plugin… No no it’s working great however i don’t know how to handle ajax requests. The problem is when a timedout user triggers any ajax call because then any redirect is returned as javascript and misinterpreted. Do you know how to force a redirect to a normal action from ajax call?

jeff at 5:51 PM on November 6 2007

Hi Mandaryn, Good question. I’ve updated the article with one possible solution. Hope this helps! -Jeff

Add a comment

You can use textile. For code, wrap in a <code lang="..."> tag.
home | services | Ruby on Rails Development | code | blog | company