2010-11-10 18 views
7

我有一个使用Devise进行认证的Rails应用程序。用户属于经销商,我想阻止谁属于残疾经销商用户能够登录。过滤能够使用Devise登录的用户

有没有一种简单的方法来扩展设计的认证取景,使其不包括已删除的经销商用户?也许在用户上使用命名范围?

干杯

特里斯坦

回答

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. 通过调用超发现在正常的方式给用户。
  2. 我正在使用STI,因此我检查用户是经销商用户,然后检查经销商是否被删除(acts_as_paranoid)。
  3. 返回用户。

这是一个非常具体的解决方案,但您可以覆盖find_for_authentication,但是您可以重写find_for_authentication,只要您事后返回用户即可。

+2

2013年中期,这仍然有效。 – 2013-05-17 05:30:51

4

搜索Stackoverflow.com给我这个提问/回答:Custom authentication strategy for devise

基本上,你必须实现在监狱长的水平自定义的认证策略(即underlies设计)。对于我的项目,我做了以下内容:

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

希望帮助!

+0

原来我可以覆盖find_for_authentication(见下文)。尽管感谢您的回答,但可能会对我正在处理的另一个问题有所了解。 – tristanm 2010-12-15 20:20:30

相关问题