简体   繁体   中英

Devise Remember Me and Sessions

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 (ie, 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.

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

The timeout_in will automatically log you out within 10 minutes of inactivity and is incompatible with the remember_me checkbox. You can have one, but not both.

The information in previous answers is outdated. I've tested my project, which uses Rails 4 and Devise 3.5.1 and also checked devise code to be sure.

Now it looks whether Remember Me checkbox was checked:

  • if yes , it checks if remember_exists_and_not_expired , so basically uses config.remember_for for session management

  • if no , it checks if last_access <= timeout_in.ago , using config.timeout_in correspondingly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM