我的主应用程序安装了一个引擎,我想保护该引擎中的某些 Controller 和操作。
发动机安装有:
mount SomeEngine::Engine => '/some_engine'
Devise/CanCan 正在与主应用程序的其余 Controller 和操作一起工作,但让事情在没有其他任何东西的情况下运行会产生此错误:
This action failed the check_authorization because it does not authorize_resource. Add skip_authorization_check to bypass this check.
所以我使用装饰器方法从主应用程序打开引擎 Controller 并添加:
load_and_authorize_resource
然后我得到这个错误:
No route matches {:action=>"new", :controller=>"devise/sessions"}
我可以使用以下方法使事情正常进行,但是当我尝试实现角色时它很笨拙:
authenticate :administrator do
mount SomeEngine::Engine => '/some_engine'
end
笨拙我的意思是我必须在 routes.rb 文件中为每个有权访问引擎的角色重现上面的代码块......除非有另一种方法来使用我不知道的角色进行身份验证? ??
如果可能,我想在 Controller 中使用正常的 Devise/CanCan 授权/身份验证方法。但我认为出现“无路由匹配”错误是因为引擎不知道如何访问主应用程序的设计 Controller 。但是我如何从主应用程序中解决这个问题?
再添加一个问题......引擎中有一个特定的 Controller / Action ,我确实想向所有用户公开。到目前为止,我刚刚在 routes.rb 文件中的验证代码块之前添加了这个。
match '/some_engine' => 'some_engine/some_controller#public_action'
它可以工作......但是这条线与 routes.rb 中的 block 似乎我做错了什么。而且它不允许我很好地实现角色。
最佳答案
您可以从主应用程序继承应用程序 Controller 以供使用设计和 cancan。
module SomeEngine
class ApplicationController < ::ApplicationController
before_filter :merge_abilities
private
def merge_abilities
current_ability.merge(SomeEngine::Ability.new(current_user))
end
end
end
在此之后,您可以通过创建自己的方式为引擎创建能力。
module SomeEngine
class Ability
include ::CanCan::Ability
def initialize(user)
return if user.nil?
can :manage, SomeModel
end
end
end
SomeModel
( SomeEngine::SomeModel
) 是 SomeEngine
的模型引擎。在资源 Controller 中,您必须指定资源的类名。
load_and_authorize_resource class: SomeEngine::SomeModel
并且不要忘记将路由助手更改为
main_app.MAIN_APP_PATHS
如果您想在引擎中使用它,请在主应用程序布局中使用它。
关于ruby-on-rails - 如何使用 Devise/CanCan 保护已安装的 Engine 资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12208448/