Skip to content

How To: Add :lockable to Users

Igor Zubkov edited this page Feb 5, 2024 · 14 revisions

If you find yourself needing to introduce lockable to your User model (stored as the users table) after the application has already been used for sometime.

First, update the lockable configuration properties in config/initializers/devise.rb to your liking.

  # ==> 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 = [ :email ]

  # 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 = :both

  # Number of authentication tries before locking an account if lock_strategy
  # is failed attempts.
  config.maximum_attempts = 20

  # 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

Also you may need to set paranoid mode to false if the last attempt warning message does not show. NB this has other effects you should consider.

  config.paranoid = false

Then, add devise :lockable to your models/user.rb file

devise :registerable, :lockable

Then, create the migration as:

rails g migration add_lockable_to_devise

Will generate db/migrate/YYYYMMDDxxx_add_lockable_to_devise.rb. Add the following to it in order to do the migration.

class AddLockableToDevise < ActiveRecord::Migration
  def change
    add_column :users, :failed_attempts, :integer, default: 0, null: false # Only if lock strategy is :failed_attempts
    add_column :users, :locked_at, :datetime

    # Add these only if unlock strategy is :email or :both
    add_column :users, :unlock_token, :string
    add_index :users, :unlock_token, unique: true
  end
end

You can also Generate views if haven't already

rails generate devise:views users

Do the migration rake db:migrate

Restart the server.

Clone this wiki locally