Ben Downey
Ben Downey

Reputation: 2665

Security: using CanCan to make sure user cannot see other users' profiles

I've got an app that uses Devise, CanCan and Rolify to deal with authentication and authorization. But I don't think I'm using these gems to the full extent. Right now the only thing in my ability class is this:

class Ability

  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
    if user.has_role? :admin
      can :manage, :all
    else
      can :read, :all
    end
  end
end

I found a security hole where an authenticated user is able to look at other user profiles. I fixed it by changing some code in the user controller.

def show
  @user = current_user.has_role?(:admin) ? User.find(params[:id]) : current_user
end

Is this the best way to deal with this hole? Is there a best practice or a rails convention that addresses this in a different way?

Upvotes: 1

Views: 180

Answers (1)

apneadiving
apneadiving

Reputation: 115521

From the doc:

can :read, ModelName, :user_id => user.id

Upvotes: 2

Related Questions