LoginSignup
18
18

More than 5 years have passed since last update.

deviseで後からアカウントロックを追加する

Last updated at Posted at 2018-09-25

背景

deviseにてログイン機能を持っているWebシステムに対して、
アカウントロック機能を後から追加する必要があった
※アカウントロック機能:パスワード入力を規定の回数間違えた場合、一定時間アカウントを凍結する

前提

  • deviseを使用したRailsプロジェクトが既にある
  • ログイン機能が実装されている
  • Docker上でRailsを起動させている

手順

deviseの設定

config/initializers/devise.rbにアカウントロックの設定を記載する

devise.rb
  # ==> Configuration for :lockable
  # Defines which strategy will be used to lock an account.
  # :failed_attempts = Locks an account after a number of failed attempts to sign in.
  # :none            = No lock strategy. You should handle locking by yourself.
  # アカウントロック機能を使用するか
  config.lock_strategy = :failed_attempts

  # Defines which key will be used when locking and unlocking an account
  # ロック、アンロックに使用するキー項目を指定(今回は独自に追加した項目を指定)
  config.unlock_keys = [:user_id]

  # Defines which strategy will be used to unlock an account.
  # :email = Sends an unlock link to the user email
  # :time  = Re-enables login after a certain amount of time (see :unlock_in below)
  # :both  = Enables both strategies
  # :none  = No unlock strategy. You should handle unlocking by yourself.
  # アンロックする方法を選択(今回は一定時間経過するとアンロックするよう設定)
  config.unlock_strategy = :time

  # Number of authentication tries before locking an account if lock_strategy
  # is failed attempts.
  # アカウントロックまでの試行回数を設定
  config.maximum_attempts = 6

  # Time interval to unlock the account if :time is enabled as unlock_strategy.
  # アカウントをアンロックする時間を設定
  config.unlock_in = 1.hour

  # Warn on the last attempt before the account is locked.
  # アカウントロック前の最後の試行で警告するか選択(今回は警告ありを設定)
  config.last_attempt_warning = true

モデルに:lockableの指定を追加

アカウントのモデルにdeviseの機能を有効にする記載があるため、:lockableを追加する

  devise :database_authenticatable, :registerable, :lockable,
         :recoverable, :rememberable, :trackable, :validatable

migrationを実行

アカウントロック用のカラムをDBに追加するため、マイグレーションファイルを作成する

rails g migration add_lockable_to_devise

「db/migrate/YYYYMMDDxxx_add_lockable_to_devise.rb」が作成されるので、

追加するカラムの内容を記載する

    add_column :users, :failed_attempts, :integer, default: 0, null: false # Only if lock strategy is :failed_attempts
    add_column :users, :unlock_token, :string # Only if unlock strategy is :email or :both
    add_column :users, :locked_at, :datetime
    add_index :users, :unlock_token, unique: true

migrateを実行してカラムを追加する

rails db:migrate

Railsを再起動

Railsを再起動する
今回はDocker上で動いているため、コンテナを再起動させる

感想

後からアカウントロックを追加するHow Toを参考にしたらめちゃくちゃ簡単だった
メールアドレスで管理する運用をしていないから経過時間でアカウントロックを解除させているけど、今度はメールでリンクURLを送るパターンもやってみたい

18
18
0

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
18
18