2016-11-04 43 views
0

我有一個rails應用程序,我在其中添加了一個名爲'authorized'的布爾字段給用戶模型。基本上,我想鎖定應用程序,只有授權用戶才能訪問應用程序。我試圖做到這一點在我的應用控制器:在設計中檢查授權標誌

class ApplicationController < ActionController::Base 
    protect_from_forgery with: :exception 

    def authorized 
    redirect_to root_path, alert: "Not Authorized" if !current_user.authorized? 
    end 

end 

然而,當我這樣做,因爲我有設置到需要驗證的路徑的根本途徑我得到一個重定向錯誤。

我現在可以在視圖或其他控制器中執行此檢查,但是我想在應用程序控制器中執行此操作,因爲我希望整個應用程序都處於鎖定狀態。

+0

寫入的代碼片段將用戶重定向到th如果當前用戶被授權,則爲root_path。那是對的嗎? –

+0

Opps!你是對的...現在修好了。 – Lumbee

回答

0

這裏是我的解決方案...

在我想要的 '授權' 認證我添加了控制器...

before_filter :authorized, :except => :not_authorized 

... 

def authorized 
    if !current_user.authorized? 
     redirect_to not_authorized_path 
    end 
end 

在我的路線,我說..

get 'not_authorized' => 'my_controller#not_authorized' 

...並添加了一個簡單的應用程序/ views/my_controller/not_authorized.html.erb

0

您可以在用戶模型中重寫這些方法。

def active_for_authentication? 
    super && approved? 
    end 

    def inactive_message 
    'my custom inactive message' unless approved? 
    super 
    end 

我建議你通過批准更改授權名稱,我不確定但授權聲音像內部Devise方法名稱。