简体   繁体   English

CanCanCan:仅允许管理用户个人资料

[英]CanCanCan: Allowing to manage only users profile

I have User model on which I use device and cancancan. 我有使用设备和cancancan的用户模型。 Here is my ability: 这是我的能力:

 if user.role? :patient can :access_profile, User, :id => user.id end 

where access_profile alias is: access_profile别名为:

 alias_action :show, :edit, :update, :destroy, :to => :access_profile 

In my users_controller I use load_and_authorize_resource. 在我的users_controller中,我使用load_and_authorize_resource。 For example when I try "users/4" and current_user.id = 3 I am able to get there. 例如,当我尝试“ users / 4”并且current_user.id = 3时,我就可以到达那里。

In logs i see this: 在日志中,我看到以下内容:

 User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 4]] User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 3]] Rendered users/show.html.erb within layouts/application (0.4ms) 

Here first query comes from set_user method. 这里的第一个查询来自set_user方法。 I guess the second query loads my resource to authorize. 我猜第二个查询将加载我的资源以进行授权。 And here since current_user.id = 3 and in 2nd query i see 3 too, i guess that is why I am authorized. 在这里,由于current_user.id = 3,在第二个查询中我也看到3,我想这就是为什么我被授权了。 But id in 2nd query must be 4, i guess. 但是我想第二个查询中的id必须是4。

What to do in order to load_and_authorize method work properly. 为了使load_and_authorize方法正常工作该怎么做。

Are you sure that automatic loading of instance works ? 您确定自动加载实例有效吗? Cancancan will use Class as the object to check ability if instance can not be loaded and access to Class will always return true if defined (regardless parameters like :id ) 如果无法加载实例,Cancancan将使用Class作为对象来检查功能,并且如果定义,对Class的访问将始终返回true(无论诸如:id那样的参数)

Change load_and_authorize_resource to load_resource and check if authorize! :access_profile, @user 将load_and_authorize_resource更改为load_resource并检查是否authorize! :access_profile, @user authorize! :access_profile, @user used in access_profile action will also protect the access. authorize! :access_profile, @user在access_profile操作中使用的@user也将保护访问。

You can also define ability on instance directly: can :access_profile, user instead of defining on User class. 您也可以直接在实例上定义能力: can :access_profile, user而不是在User类上定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM