2016-08-02 143 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'的用户模型 –

相关问题