在我的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)
。 这个怎么做? 我是新手,请帮忙
此类行为的最佳解决方案是在控制器中添加一个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?}
,如果未定义别名,请删除?
)
设备中有一个专门用于该页面的Wiki页面,
https://github.com/plataformatec/devise/wiki/操作方法:-Protect-Resque-Web-with-Devise
终于这对我有用
# 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