如何使用 Devise 锁定用户?

问题描述 投票:0回答:1

我想在我的应用程序中为帐户持有者用户添加订阅类型功能,这样在登录尝试失败几次的情况下,他们将无法访问其帐户。注意:我不想从数据库中删除他们的帐户。我已经在我的应用程序中安装了

devise-2.1.2
。有谁知道如何做到这一点吗?我是
Ruby on rails
的新手,所以如果您解释一下步骤,这对我会非常有帮助。

ruby-on-rails devise authorization ruby-on-rails-3.2
1个回答
35
投票

Devise 有一个内置解决方案,可在

Devise 可锁定文档
中检查 :lockable

选项

您必须将

lock_strategy
设置为
:failed_attempts.

步骤1 设置要使用的 config/initializers/devise.rb:

# 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

第2步 您应该将可锁定项添加到您的模型中,如下所示:

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

第3步 生成迁移以使设备正常工作

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

问候!!

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.