LoginSignup
48

More than 5 years have passed since last update.

Deviseでセッションのタイムアウトまでの時間を延ばす方法

Last updated at Posted at 2014-12-29

1. 概要

Deviseのセッションのタイムアウトまでの時間は、デフォルトで30分と、サービスの性質によっては短い場合もある。
ここでは、タイムアウトまでの時間を延ばす方法について示す。

2. 動作環境

$ bundle exec gem list | grep devise
devise (3.4.1)

3. 方法

以下の3つの手順がある。

(1) モデルにdevise :timeoutableを設定する
(2) initializers で config.timeout_inを設定する
(3) flashの不要なメッセージを削除する

(1) モデルの設定

DeviseにはTimeoutableというモジュールがある。
以下のように、モデルの設定に:timeoutableを追加する。

app/models/user.rb
class User < ActiveRecord::Base
  devise ..., :timeoutable
end

原理としては、最後にアクセスした時間をセッションに記憶しておき、これと2で設定する時間との差分からタイムアウトかどうか判断している。
そのため、マイグレーションを追加する必要はない。

(2) initializersの設定

timeout_inの値は、標準では30分に設定されている。
この数値を変更することで、タイムアウトまでの時間を延ばすことができる。

config/initializers/devise.rb
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
config.timeout_in = 1.hour

(3) flashの削除

以上まででタイムアウトの時間を延ばすことはできる。
ただ、Deviseの実装の都合上、タイムアウト時にflash[:timedout] = trueという不要なflashが格納されてしまう。

flashを表示している場合、これを削除する必要がある。
flashの表示方法は様々なので、ここでは一例を示す)

app/views/layouts/_flash.html.haml
- if flash.any?
  - flash.each do |key, value|
    - next if key == 'timedout'

    ...

参考

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
48