How to lock users using Devise?

2019-02-21 14:01发布

问题:

I want to add a subscription type functionality in my application for the account holder users such that after a fixed interval of time they will not be able to access their account? Note: I dont want to delete their account from the database. I've already installed devise-2.1.2 in my application. Do any body have any idea how can it be done? I am newbie to Ruby on rails so it will be very helpful to me if you please explain the steps.

回答1:

Devise have a buil-in solution with the :lockable option check in the Devise Lockable Documentation

You have to set the lock_strategy set to :failed_attempts.

Step 1 Set your config/initializers/devise.rb to use:

# Defines which strategy will be used to lock an account.
config.lock_strategy = :failed_attempts

# Defines which key will be used when locking and unlocking an account
config.unlock_keys = [ :time ]

# Defines which strategy will be used to unlock an account.
# :time  = Re-enables login after a certain amount of time (see :unlock_in below)
config.unlock_strategy = :time

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

# Time interval to unlock the account if :time is enabled as unlock_strategy.
config.unlock_in = 2.hours

Step 2 Your should add the lockable to you Model as this:

class Example < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, 
         :lockable

Step 3 Generate the migrations to make devise work

class AddLockableToExamples < ActiveRecord::Migration
  def change
    add_column :examples, :failed_attempts, :integer, default: 0
    add_column :examples, :unlock_token, :string
    add_column :examples, :locked_at, :datetime
  end
end

Regards!!