在 Rails 中检查 CanCan 能力的适当方法是什么?
在我的应用程序中,我有多个用户角色;客户、销售人员、管理员和超级管理员。在我的能力课中,我根据这些角色定义了各种能力。
我当前为销售人员定义的唯一角色如下:
# Salesperson Abilities
if user.role == 'salesperson'
can :create, User, :role => 'customer'
end
不幸的是,以下检查始终返回 true,允许销售人员创建任何用户,无论角色如何:
can? :create, User, :role => @user.role
我已经运行了许多测试,验证当前用户的角色,以及正在创建的角色,并且无论我在 :role
条件中放置什么角色,能力检查始终返回 true。如果我完全删除该功能,或者使用 cannot
定义,则检查将返回 false,因此我知道正在应用条件中的功能。
我是否没有正确定义或检查能力条件?谢谢。
更新
我注意到,如果我尝试使用 authorize! 来授权该功能! :create, @user
,应用条件。如果我在控制器类的顶部定义 load_and_authorize_resource
,它们也会被应用。似乎只有当我尝试在控制器内部的条件下使用 can?
方法时,这些才会失败。
In my application, I have several user roles; customer, salesperson, admin, and superadmin. In my ability class, I've defined various abilities based on these roles.
The only role I currently have defined for a salesperson is as follows:
# Salesperson Abilities
if user.role == 'salesperson'
can :create, User, :role => 'customer'
end
Unfortunately, the following check always returns true, allowing a salesperson to create any user, regardless of role:
can? :create, User, :role => @user.role
I've run a number of tests, verifying both the current user's role, and the role being created, and regardless of what role I place in the :role
condition, the ability check always returns true. If I remove the ability altogether, or if I use a cannot
definition, the check returns false, so I know that the abilities within the conditional are being applied.
Am I not defining or checking the ability conditions properly? Thanks.
Update
I've noticed that if I attempt to authorize the ability using authorize! :create, @user
, the conditions are applied. They are also applied if I define load_and_authorize_resource
at the top of the controller class. It seems that these only fail when I attempt to use the can?
method with conditions inside of a controller.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在文档中,我发现了以下内容:
在这种情况下,解决方案是不检查类的权限,而是检查实例的权限,例如
can? :create、@user
或可以吗? :创建,用户.new
In the documentation I found the following:
In this case, the solution is to not check permissions on the Class but on an instance instead, e.g.
can? :create, @user
orcan? :create, User.new
这个逻辑不属于能力的范畴。该能力应该定义如何修改对象的规则,而不是可以修改这些对象内部的哪些数据。该逻辑属于您的用户模型,因为它正在处理模型的实际数据及其保存方式。这有道理吗?
This logic does not belong inside of an ability. The ability should define the rules for how objects are modified, not which data can be modified inside of these objects. This logic belongs in your User model, since it is handling the actual data of the model and how it is saved. Does this make sense?