48

This seems simple: I am trying to get my rails Active Record session to timeout after 2 minutes. So after two minutes I want my users to have to re-login.

I'm just running rails server (i.e. WebBrick) on my local dev machine.

I know this is something to do with the following code in config/initalizers/session_store.rb, but I don't think I have quite nailed it:

CodedOn::Application.config.session_store :active_record_store

CodedOn::Application.configure do
    config.action_controller.session = {:expire_after => 2.minutes}
end

This doesn't seem to work, or at least my session doesn't appear to timeout. I can't find much about the Rails 3 way to do this as I know things have changed from Rails 2.x.

Can some one help me out?

0

6 Answers 6

49

I think you will have to do this manually since the active record store does not implement the expire_after option. So within your (I assume) before filter, you should do this:

def authenticate
  if session[:logged_in]
    reset_session if session[:last_seen] < 2.minutes.ago
    session[:last_seen] = Time.now
  else
    ... authenticate
    session[:last_seen] = Time.now
  end
end

Obviously, this is not complete, but it should give you the basic idea.

UPDATE:

It seems that the functionality IS present in rails since version 2.3. I found the relevant code here. This is AbstractStore which should serve as base class for all derived ones. So, as dadooda suggests, the following should work:

Some::Application.config.session_store :active_record_store, {
  expire_after: 24.hours,
}
7
  • 1
    One question here is how does this work...as in, say this before_filter is called when the session is initially created - i.e. when the user is first authenticated, how is session[:last_seen] ever called again? If it's an authenticate before_filter, is it not called just once - on authentication? I guess what I am trying to figure out in my head is, once the session is created and the user is logged in, how do I check session[:last_seen] so that if it exceeds X amount of minutes, it forces them to re-login, without doing it at the initial creationg of the session. Hope that makes sense Commented Oct 10, 2011 at 8:11
  • 1
    I hope I got your question: HTTP is stateless. The webserver therefore does not see any relationship between any two requests. But there are use cases which demand that relationship (for example authentication). In rails, the session hash provides that. But the controllers do have to read the session hash for every request in order to recognize previously authenticated users. So the 'authenticate'-before filter is called before every request. I hope this helps.
    – moritz
    Commented Oct 10, 2011 at 20:05
  • Given that I have written my authentication from scratch, does your answer work under the assumption that I explicitly call the before_filter on every single controller, or do I have to pass filter_resource_access on every single controller in order to force it to do that? I know that if I were using devise or some other authentication gem it would take care of this stuff for me - but given that I am writing one from scratch, that's why I am asking these questions. Commented Oct 10, 2011 at 21:50
  • Or does rails automagically call all before_filters in the application_controller before every controller request? Commented Oct 10, 2011 at 21:54
  • 1
    @marcamillion: the reason for this is because by convention your controllers all inherit from ApplicationController (e.g. class PostsController < ApplicationController), so they inherit the before_filter declarations. Commented Nov 2, 2012 at 20:04
45

I did this in simple way you can try this:

In your config/initializers/session_store.rb just do this:

Yourapp::Application.config.session_store :cookie_store, 
                                             :key => "_yourapp_session",
                                             :expire_after => 2.minutes

This is working for me finely, hope works for you also.

1
  • 2
    Works in Rails 5.0.0 as well.
    – bevanb
    Commented Jul 16, 2016 at 21:43
4

You have to do it manually. Here's an example of creating a class method for ActiveRecord sessions. You can use Rufus-Scheduler and/or DelayedJob to regularly call this.

class Session < ActiveRecord::Base
  def self.sweep(time = 1.hour)
    if time.is_a?(String)
      time = time.split.inject { |count, unit| count.to_i.send(unit) }
    end

    delete_all "updated_at < '#{time.ago.to_s(:db)}' OR created_at < '#{2.days.ago.to_s(:db)}'"
  end
end

More background on why it's important: http://guides.rubyonrails.org/security.html#session-expiry

4

mosch says:

I think you will have to do this manually since the active record store does not implement the expire_after option.

It seems it's no longer this way. :expire_after worked for me in Rails 3.2.11:

Some::Application.config.session_store :active_record_store, {
  key: "some_session_id",
  domain: ".isp.com",
  expire_after: 24.hours,
}

The cookie auto-prolongs after every request towards the app. The session persists through browser exits.

I did the above trick to "globalize" the session across domain for a simple SSO functionality, seems to work so far.

2

The expiration time.

MAX_SESSION_TIME = 60 * 60

before_filter :prepare_session

def prepare_session

   if !session[:expiry_time].nil? and session[:expiry_time] < Time.now
      # Session has expired. Clear the current session.
      reset_session
   end

   # Assign a new expiry time, whether the session has expired or not.
   session[:expiry_time] = MAX_SESSION_TIME.seconds.from_now
   return true
end
-6

Just add timeout_in method in your model and it should do the trick:

  def timeout_in
    2.minutes
  end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.