2010-11-10 22 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

相關問題