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


Answers:


149

像这样做:

创建一个名为列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

更新

正如Matt Huggins指出的那样,该方法现在称为active_for_authentication?Documentation


21
看起来这已重命名为active_for_authentication?而不是active?
马特·哈金斯

1
the method is now called active_for_authentication?表示您的方法名称应active_for_authentication?改为active?
fotanus 2014年

5
Devise
Wiki-

重要说明:active_for_authentication?必须是一种公共方法!
MladenJablanović16年

super and self.is_active?可以简化为super && is_active?
David

17

User模型中添加一列:allowed_to_log_in

然后添加到/app/models/user.rb

def active_for_authentication?
    super and self.allowed_to_log_in?
end

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

def inactive_message
    "You are not allowed to log in."
end

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

“您的帐户尚未激活。”

这使用户感到困惑,真正的原因是您已“禁止”他们登录。


我正在实现一个用户暂停功能,该功能可以正常工作,但是现在也为用户注册显示inactive_message“您的帐户当前处于暂停状态”。我可以为激活新帐户和暂停用户使用不同的非活动消息吗?
Dercni


感谢您的inactive_message评论。
克里斯·法默

0

您要执行授权,而不是验证。但是,Devise仅进行认证。
即设计仅告诉您用户就是他所说的那个人。
您还需要其他一些禁止他使用该网站的信息。

授权是一个受欢迎的话题,有很多宝石可以为您提供帮助:
http:
//ruby-toolbox.com/categories/rails_authorization.html选择。


6
我知道区别。问题是我想禁止用户登录,而不是访问某些控制器。
2011年

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.