randombits
randombits

Reputation: 48430

Rails: authorizing user with CanCan gem issue

I have an action in my controller that looks like the following:

  def show
    @user = User.find(params[:user_id])
    # ... more stuff.
  end

Note, I'm overriding the loading of the resource as CanCan tries to load with params[:id] and I need to use params[:user_id] here.

The top of my controller has the following defined:

  authorize_resource :only => [:show]

And in Ability.rb:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new
    can :show, User if :id == user.id
  end
end

All of my invocations are unauthorized however. I'm using devise for authentication and I'm verifying that the user object being passed into initialize is indeed the logged in user. How do I verify that the logged in user is only able to view the profile for which they are requesting and no other profile?

Upvotes: 0

Views: 231

Answers (1)

mark
mark

Reputation: 10564

You're not overriding the loading of the resource as this is taking place before the action:

authorize_resource :only => [:show]

Instead you need to remove it and add the authorisation to your action or a separate before_filter.

def show
  @user = User.find(params[:user_id])
  authorize! :show, @user

Upvotes: 1

Related Questions