Rails: Devise Session Expiry with SessionsController < Devise::SessionsController

824 views Asked by At

The Ruby on Rails Security Guide on Security, under "2.9 Session Expiry" gives following example code:

class Session < ApplicationRecord
  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)}'"
  end
end

How do I connect the model to Devise / to the Devise SessionController? Will Devise use the model? Will it do so automatically or are further steps necessary? Isn't this example specific to Rails' own cookie/session management? If so, what would be the proper complement with Devise / Warden?

1

There are 1 answers

0
ScottM On BEST ANSWER

Those instructions are really useful if you’re building your own auth system, but Devise can handle this for you.

In your user model, add the :timeoutable attribute to your existing devise statement.

In config/initializers/devise.rb, you can then specify the timeout duration, e.g.:

config.timeout_in 30.minutes

If a one-size-fits-all timeout limit doesn’t meet your needs, you have a couple of other options:

  1. If you have different models that have their own sign in paths and different timeout limits, you can add timeout_in to each devise_for declaration

  2. If you have a flag in your user model (e.g., some users have admin: true) you can add a #timeout_in method to your model (see this entry in the Devise wiki).

Most of the time, though, using the config file is the best, and easiest, way to go.