如何使用Devise锁定用户?

14

我想在我的应用程序中为账户持有者用户添加订阅类型功能,这样,在少数登录尝试失败之后,他们将无法访问其账户。注意:我不想从数据库中删除他们的账户。我已经在我的应用程序中安装了devise-2.1.2。有没有人知道怎么做?我是Ruby on Rails的新手,所以如果您能解释一下具体步骤,那对我来说将非常有帮助。

1个回答

33

Devise在Devise Lockable Documentation中提供了内置的解决方案,使用: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

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

lockable

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

步骤 3 生成迁移以使 Devise 工作

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

问候!


我想澄清一下,失败的尝试只适用于某个用户尝试注册特定次数的情况。 - Ahmad hamza
1
这应该仅用于登录块,另一件事是您的应用程序逻辑的一部分,您应该自己实现它。 - felipeclopes
1
我加了一个逐步说明来帮助你,很可能这就是你所需要的! - felipeclopes
1
你发表了很好的答案,这对我非常有帮助。 :) - Jigar Bhatt
1
应该添加索引吗? add_column :examples, :unlock_token, :string, index: true - AndreiMotinga
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接