2016-08-02 141 views
1

在我的rails應用程序中,我使用devise進行身份驗證,我的模型名稱爲user,對此,我有一個布爾字段admin。在我的routes.rb中,我試圖限制除管理員以外的所有用戶訪問網址。只允許管理員用戶訪問一個resque web界面

mount Resque::Server.new, :at => "/resque" 

。我試着用色器件的CURRENT_USER幫手像

mount Resque::Server.new, :at => "/resque" if current_user.admin == true 

但是得到了錯誤undefined local variable or method 'current_user' for #<ActionDispatch::Routing::Mapper:0x000000053ac780> (NameError) 。這個怎麼做?我是新來的導軌請幫助

+0

你的路由不知道什麼工作會話或登錄用戶。 – Alfie

回答

0

最後這對我來說

# routes.rb 
    match "/resque" => Resque::Server, :anchor => false, :constraints => lambda { |req| 
    req.env['warden'].authenticated? and req.env['warden'].user.is_admin? 
    } 

    # user.rb 
    class MUserLogin < ActiveRecord::Base 
    . 
    . 
    . 
    def is_admin? 
     # your admin logic here for example: 
     self.admin == true 
    end 
    end 
1

爲這種行爲的最好的解決辦法是增加一個before_action到你的控制器,這將產生一個錯誤,如果用戶是不是管理員:

before_action:authorize_admin_only

def authorize_admin_only 
    raise RoutingError.new('Not found') if !current_user.admin 
end 

您的路線文件在啓動時會被解釋一次,即使您可以找到路線取決於請求的方法(例如,使用routing_filter),將其用於授權目的也不是一個好主意。

authorize_admin_only中,您還可以呈現錯誤文件或將用戶重定向到其他頁面,例如,登錄。

針對您的特殊情況下,如你想安裝另一個引擎,你也可以在admin模型中定義的認證in your routes(和special resque example

authenticate :admin_user do #replace admin_user(s) with whatever model your users are stored in. 
    mount Resque::Server.new, :at => "/jobs" 
    end 

如果沒有管理員模式,那麼你可以參考the devise documentation for authenticate,做這樣的事情:

authenticate(:user, &:admin?) do 
    mount Resque::Server.new, :at => "/jobs" 
end 

&:admin?產生相同的結果lambda{|user| user.admin?},刪除?如果你二叔□不定義這種別名)

+0

我正在嘗試裝載resque gem的網絡界面。所以我不能這樣做 –

+0

@TonyVincent我發現了一個使用這種方式設計的例子,雖然你也可以使用'routing_filter'並定義一個自定義過濾器:) – Geoffroy

+0

問題是沒有單獨的admin_user模型,我擁有的是一個布爾型字段'admin'的用戶模型 –

相關問題