如何使用CanCanCan授权名称空间,无模型的控制器? [英] How to authorize namespace, model-less controllers using CanCanCan?
问题描述
使用CanCanCan为命名空间,无模型的控制器授权和检查功能的正确方法是什么?
What is the correct way to authorize and check abilities for a namespaced, model-less controller using CanCanCan?
经过大量的搜索和阅读Wiki之后,我目前拥有
After much googling and reading the wiki, I currently have
#controllers/namespaces/unattacheds_controller.rb
def Namespaces::UnattachedsController
authorize_resource class: false
def create
# does some stuff
end
end
#models/ability.rb
def admin
can [:create], :namespaces_unattacheds
end
#view/
<%= if can? :create, :namespaces_unattacheds %>
# show a create form to authorized users
<% end %>
这没有正确授权控制器.管理员可以看到条件创建表单,但无权发布到创建操作.
This is not correctly authorizing the controller. Admins can see the conditional create form, but are not authorized to post to the create action.
post :create, valid_params
Failure/Error: { it { expect( flash ).to have_content "Successfully created" }
expected to find text "Successfully created"
got: "You are not authorized to access this page."
在一个示例中,Wiki建议为命名空间控制器创建一个单独的Ability类. https://github.com/CanCanCommunity/cancancan/wiki/Admin-Namespace
In one example, the wiki suggests creating a separate Ability class for a namespaced controller. https://github.com/CanCanCommunity/cancancan/wiki/Admin-Namespace
有没有更简单的方法来实现这一目标?这个应用程序使用了许多命名空间控制器,我真的不想为每个控制器创建一个能力类.
Is there a simpler way to achieve this? This app uses many namespaced controllers, I don't really want to create an ability class for each one.
是否有正确的语法引用Ability类中的命名空间控制器?
Is there correct syntax to refer to the namespaced controller in the Ability class?
can [:create], Namespaces::Unattacheds
can [:create], :namespaces_unattacheds
can [:create], namespaces/unattacheds
????
推荐答案
也许不是最漂亮的解决方案,但我设法通过添加
Maybe not the prettiest solution but I managed to achive this by adding
skip_authorization_check
before_action { raise CanCan::AccessDenied unless current_user.can?(params[:action].to_sym, ::namespaces_unattacheds) }
如果您这样做,则可以将所需的任何内容从该控制器传递给能力类.
If you do it like this, you can pass whatever you want from this controller to the ability class.
您需要添加罐头吗?首先使用此方法的方法 https://github.com/CanCanCommunity/cancancan/wiki/其他用户的能力
You need to add the can? method first to be able to use this https://github.com/CanCanCommunity/cancancan/wiki/Ability-for-Other-Users
这篇关于如何使用CanCanCan授权名称空间,无模型的控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!