Delete a Clearance session after some time of inactivity

Updated . Posted . Visible to the public.

This note describes how to kick a user out of a Rails application after she hasn't requested an action for a while. Note that this is different from deleting sessions some time after the last login, which is the default.

Also note that this is probably a bad idea. Most sites keep sessions alive forever because having to sign in again and again is quite inconvenient for users and makes your conversion rates go down the toilet. The Clearance default is to keep sessions around for one year (and should be much longer).

Anyway, let's assume you're designing an online banking site, you are using Clearance Show archive.org snapshot for authentication, and you need to kick people out of your system after idling for one hour. You want to make this Cucumber feature go green:

Scenario: Users are kicked out of the system after one hour of inactivity
  When I sign in
    And it is 50 minutes later
    And I go to the homepage
  Then I should be signed in
  When it is 65 minutes later
    And I go to the homepage
  Then I should not be signed in

Configure your Clearance in config/initializers/clearance.rb like this:

Clearance.configure do |config|
  # ...
  config.cookie_expiration = lambda { 1.hour.from_now.utc }
end

Now run a before filter for every incoming request that refreshes the cookie's expiration date:

class ApplicationController < ActionController::Base
  include Clearance::Authentication

  before_filter :refresh_authentication

  def refresh_authentication
    sign_in(current_user)
  end

end

The feature should be green now.

Henning Koch
Last edit
Keywords
minutes, hours, idle, idling
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2011-07-21 10:41)