【问题标题】:Allow only admin users to access a resque web interface仅允许管理员用户访问 resque Web 界面
【发布时间】:2016-08-02 06:46:00
【问题描述】:

在我的 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) .这该怎么做?我是rails新手,请帮忙

【问题讨论】:

  • 您的路线不知道会话或登录用户。

标签: ruby-on-rails devise routing resque


【解决方案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?} 相同的结果,如果您没有定义这样的别名,请删除?

【讨论】:

  • 我正在尝试安装 resque gem 的 Web 界面。所以我不能这样做
  • @TonyVincent 我找到了一个使用这种方式设计的示例,尽管您也可以使用 routing_filter 并定义自定义过滤器:)
  • 问题是没有单独的 admin_user 模型,我拥有的是一个带有布尔字段 'admin' 的用户模型
  • @TonyVincent 更新了您需要的更精确的内容
  • 感谢@Geoffroy 的支持,终于搞定了
【解决方案2】:

在设备中有一个专门用于此的 wiki 页面,

https://github.com/plataformatec/devise/wiki/How-To:-Protect-Resque-Web-with-Devise

【讨论】:

  • 我遇到了这个页面,但据我了解,它显示了如何在访问该页面之前对用户进行身份验证,我想只允许管理员用户访问该页面
【解决方案3】:

最后这对我有用

  # 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多