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

时间:2010-11-10 03:56:00

标签: ruby-on-rails devise

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

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

干杯

特里斯坦

2 个答案:

答案 0 :(得分:15)

原来我需要做的就是覆盖我的用户模型的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. 退回用户。
  4. 对于我的场景,这是一个非常具体的解决方案,但是您可以覆盖find_for_authentication但是如果您愿意,那么之后您将返回该用户。

答案 1 :(得分:4)

搜索Stackoverflow.com给了我这个问题/答案:Custom authentication strategy for devise

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

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

您可以在此处详细了解自定义看守策略:https://github.com/hassox/warden/wiki/Strategies

希望有所帮助!