开发者

Rails: authorizing user with CanCan gem issue

开发者 https://www.devze.com 2023-04-01 09:34 出处:网络
I have an action in my controller that looks like the following: def show @user = User.find(params[:user_id])

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 开发者_Go百科profile?


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
0

精彩评论

暂无评论...
验证码 换一张
取 消