2014-11-08 240 views
0

我重寫了設計的註銷路徑並將其設置爲request.referer。問題在於如果用戶在具有authenticate_user的頁面上!在應用過濾器之前,我被髮送到登錄頁面並顯示錯誤。這並不理想,我想只在用戶來自具有驗證要求的路徑時才重定向到root_path。做這個的最好方式是什麼?註銷設計的重定向路徑

回答

0

我最終檢查了引用者url所關聯的控制器的回調。如果有任何authenticate_*!回調,則會分別檢查它們以查看@if實例變量中是否指定了任何操作。如果沒有,則回調將應用於所有操作,並且我們知道引用網址來自受限操作。如果有指定的動作,我們使用正則表達式來檢查引用動作是否受限制。

滿足條件的任何回調都會添加到數組中。在循環回調之後,我們檢查該數組是否爲空。如果是,我們將用戶發回request.referer。如果它不是空的,這意味着將它們發送到request.referer會將它們重定向到登錄頁面並顯示錯誤。在這種情況下,我們將用戶發送至root_path

如果發生任何錯誤,用戶將被髮送到root_path

下面是代碼:

def after_sign_out_path_for(resource_or_scope) 
    begin 
    controller_name = Rails.application.routes.recognize_path(request.referer)[:controller] 
    controller_class = "#{controller_name}_controller".camelize.constantize 
    authentication_callbacks = controller_class._process_action_callbacks.select { |callback| callback.filter.match /authenticate_\w+!/ } 
    action_name = Rails.application.routes.recognize_path(request.referer)[:action] 

    restricting_callbacks = [] 

    authentication_callbacks.each do |callback| 
     callback_scope = callback.instance_variable_get(:@if) 
     if callback_scope.empty? || callback_scope.first.match(/action_name\s==\s(\'|\")#{Regexp.quote(action_name)}(\'|\")/) 
     restricting_callbacks << callback 
     end 
    end 

    restricting_callbacks.empty? ? request.referer : root_path 
    rescue Exception => e 
    request.referer 
    end 
end