Using CanCan to restrict viewing on user_id index page

I use Devise and Cancan for rails 3.2.6. In the application, I allow users to create a document with some information collected in the form. Then I want to allow the user to list only their documents that work on the document index page on localhost: 3000 / users / 1 /. What does not work, I try to deprive the user of the ability to see all other documents by replacing / users /: id / documents with a different number.

I use cancan and tried both

can: index, Document ,: user_id => user.id can: read, Document,: user_id => user.id

and then in the document controller index method

if can? :read, Document @documents = @user.documents else redirect_to root_path end 

also tried with :index , but this does not work. I also use load_and_authorize_resource ..

Any thoughts on what I'm missing?

I will say that cancan works for my user and user controller to create, edit and edit users, so I know that cancan works in general. It also works to update and delete user documents. This is just an index function not working.

 class Ability include CanCan::Ability def initialize(user) user ||= User.new # guest user (not logged in) if user.id if user.has_role? :user can :create, Document can :read, Document, :user_id => user.id can :update, Document, :user_id => user.id end end end end 
+4
source share
2 answers

You must make sure that users who are not logged in, as well as users whose user.id does not match the document user_id (owner of the document), do not have permission to read all documents.

 class Ability include CanCan::Ability def initialize(account) user ||= User.new #non-logged-in user # logged in users if user.id and user.has_role?(:user) #content owners can :manage, Document, :user_id => user.id #other logged-in users can [:show, :create], Document end end end 

Be careful, you do not have a line like can :read, :all or can :read, Document , most likely you will give permission somewhere if you said that cancan already works.

+2
source

In your case, you should write in your class of features

 def initialize(user) can :manage, Document do |document| document.user == user end end 

This will check if the document belongs to a registered user or not. If so, it can return true, otherwise false.

More on how to handle complex authorization using the block,

https://github.com/ryanb/cancan/wiki/Defining-Abilities-with-Blocks

0
source

Source: https://habr.com/ru/post/1434657/


All Articles