仅允许管理员用户访问Resque Web界面

问题描述 投票:1回答:3

在我的rails应用程序中,我正在使用devise进行身份验证,并且我的模型名称是user ,我具有一个布尔字段admin 。 在我的routes.rb ,我试图限制除管理员以外的所有用户访问URL。

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

。 我尝试使用像devise的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)得到了错误的undefined local variable or method 'current_user' for #<ActionDispatch::Routing::Mapper:0x000000053ac780> (NameError) 。 这个怎么做? 我是新手,请帮忙

ruby-on-rails devise routing resque
3个回答
2
投票

此类行为的最佳解决方案是在控制器中添加一个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模型上定义身份验证(以及特殊的resque示例

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

如果您没有管理员模型,则可以参考devise文档进行authenticate并执行以下操作:

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

&:admin?产生的结果与lambda{|user| user.admin?} ,如果未定义别名,请删除?


1
投票

1
投票

终于这对我有用

  # 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
© www.soinside.com 2019 - 2024. All rights reserved.