过滤能够使用Devise登录的用户

我有一个使用Devise进行身份validation的Rails应用程序。 用户属于经销商,我希望阻止属于残障经销商的用户能够登录。

是否有一种直接的方式来扩展Devise的身份validation查找器,以便它不包括已删除的经销商的用户? 也许在User上使用命名范围?

干杯

特里斯坦

事实certificate我需要做的就是覆盖我的用户模型的find_for_authentication方法:

class User < ActiveRecord::Base ... # Intercept Devise to check if DealershipUser's Dealership is active def self.find_for_authentication(conditions) user = super return nil if user.is_a?(DealershipUser) && user.dealership.deleted? user end ... end 
  1. 通过调用super以正常方式查找用户。
  2. 我正在使用STI,所以我检查用户是DealershipUser,然后检查经销商是否被删除(acts_as_paranoid)。
  3. 返回用户。

这是我的方案的一个非常具体的解决方案,但您可以覆盖find_for_authentication,但是如果您愿意,之后您将返回用户。

搜索Stackoverflow.com给了我这个问题/答案: 设计的自定义身份validation策略

基本上,您必须在Warden的级别(作为Devise的基础)实现自定义身份validation策略。 对于我的项目,我做了以下事情:

config/initializers/devise.rb

 Devise.setup do |config| config.warden do |manager| manager.default_strategies(:scope => :user).unshift :user_has_login_access end end Warden::Strategies.add(:user_has_login_access) do def valid? # pass the commit parameter as 'login' or something like that, so that this strategy only activates when the user is trying to login params[:commit] == 'login' end def authenticate! u = User.find_by_email(params[:user][:email]) if u.can_login? # retrieves boolean value stored in the User model, set wherever success! u else fail! "Account does not have login privilages." end end end 

您可以在此处阅读有关自定义Warden策略的更多信息: https : //github.com/hassox/warden/wiki/Strategies

希望有所帮助!