Devise Remember Me and Sessions

Arthur Frankel picture Arthur Frankel · Feb 17, 2011 · Viewed 23.9k times · Source

I'm confused with the devise gem config settings:

  # The time the user will be remembered without asking for credentials again.
  config.remember_for = 2.weeks

  # The time you want to timeout the user session without activity. After this
  # time the user will be asked for credentials again.
  config.timeout_in = 10.minutes

I want to have a user select the "Remember Me" checkbox (i.e., keep me logged in), but the default session timeout is 10 minutes. After 10 minutes it asks me to log in again even though I have clicked "Remember me". If this is true then the remember_for is really meaningless. Obviously I'm missing something here.

Answer

douglasr picture douglasr · May 17, 2011

Ryan is correct in that the default Devise gem does not support both the :rememberable and :timeoutable options. However, like all things Ruby, if you don't like the decision that some other coder has made, especially when it strays from the norm that most users are likely to expect, then you can simply override it.

Thanks to a (rejected) pull request we can override this behaviour by adding the following code to the top of your Devise config file (/config/initializers/devise.rb):

module Devise
  module Models
    module Timeoutable
      # Checks whether the user session has expired based on configured time.
      def timedout?(last_access)
        return false if remember_exists_and_not_expired?
        last_access && last_access <= self.class.timeout_in.ago
      end

      private

      def remember_exists_and_not_expired?
        return false unless respond_to?(:remember_expired?)
        remember_created_at && !remember_expired?
      end
    end
  end
end

This will now allow you to configure both options and have them work as you would expect.

config.remember_for = 2.weeks
config.timeout_in = 30.minutes