3
votes

I am currently using cancan in my web app and so far it works greats but there is a problem I am having regarding nested resources in rails. When accessing the index page cancan does not restrict a user from seeing what another logged in user can see. It works fine for the show pages but when visiting the index page it does not work.

routes.rb

resources :skater do
  resources :videos
end

ability.rb

can :manage, Video, :skater => { :user_id => user.id }

video_controller.rb

load_and_authorize_resource :skater
load_and_authorize_resource :video, :through => :current_user

How can I restrict access to another users index view so that user A cant view user B videos?

2
It doesn't look like you are in a nested resource. Could you please include the other load_and_authorize_resource calls you are using.Baylor Rae'
@BaylorRae' I have updated the above but did not have an effectcoletrain
@BaylorRae' I've added cannot [:read, :show], Video and it worked but when I try to view my own video it does not work I received the same error as a restricted user.coletrain

2 Answers

2
votes

Try removing :through => :current_user to see if that fixed your problem. Look at the second code example in the CanCan Wiki to see how nested resources are supposed to be used.

CanCan will grab the current user through a current_user method in your application. Because of this you don't have to define it when you are authorizing controller actions.


Update: Try using this in your controller.

load_and_authorize_resource :skater
load_and_authorize_resource :video, :through => :skater

Update 2: I can't tell if CanCan is failing because of Ability Precedence or because the current user is simply unauthorized.

Based on what I've seen so far this is how your ability.rb file should look. The second line will overwrite the first line allowing you to limit how much can be viewed and changed. I decided to use :manage because it "covers all the bases" by including all the permissions.

cannot :manage, Video # this will include :read, :show, :edit, :update, and :delete
can :manage, Video, :skater => { :user_id => user.id }

A concern of mine is that you are not filtering the skater correctly. If you have any problems I would suggest trying this.

can :manage, Video, :user_id => user.id
0
votes

You should check this question, it's the same problem as you.

Cancan nested_routes restrict acces to :index