设计 - 我如何禁止某些用户登录?

Dim*_*eff 102 ruby-on-rails devise

我在我的应用程序中使用Devise进行身份验证.

我如何禁止某些用户登录 - 禁用某个用户?

Zab*_*bba 141

像这样做:

创建一个is_activeUser模型调用的列.

然后将以下代码添加到User模型中:

class User < ActiveRecord::Base
  #this method is called by devise to check for "active" state of the model
  def active_for_authentication?
    #remember to call the super
    #then put our own check to determine "active" state using 
    #our own "is_active" column
    super and self.is_active?
  end
end
Run Code Online (Sandbox Code Playgroud)

UPDATE

正如Matt Huggins所说,这个方法现在被称为active_for_authentication?(文档)

  • 看起来这已经被重命名为`active_for_authentication?`而不仅仅是`active?`. (21认同)
  • Devise Wiki-[如何在登录时自定义用户帐户状态验证](https://github.com/plataformatec/devise/wiki/How-To%3a-Customize-user-account-status-validation-when-logging-在) (3认同)
  • `super and self.is_active?` 可以简化为 `super &amp;&amp; is_active?` (2认同)

小智 16

User模型中添加一列:allowed_to_log_in.

然后将其添加到/app/models/user.rb:

def active_for_authentication?
    super and self.allowed_to_log_in?
end
Run Code Online (Sandbox Code Playgroud)

如果您想通过自定义消息通知用户,您也可以添加此消息:

def inactive_message
    "You are not allowed to log in."
end
Run Code Online (Sandbox Code Playgroud)

我认为这非常重要,因为Devise的标准信息说:

"您的帐户尚未激活."

这对用户来说很困惑,真正的原因是你已经"禁止"他们登录.