CanCan cannot set privileges for devise models other than User #656

Closed
zooshme opened this Issue Jun 19, 2012 · 8 comments

4 participants

@zooshme

Hi

I'm using CanCan 1.6 with Ruby 1.9.2 and Rails 3.2.3. I've tried to setup different privileges for different devise models: User and Admin. This is what my Ability class looks like. But CanCan sets privileges only for the User model. Admin receives only guest privileges.

class Ability
include CanCan::Ability

def initialize(model)
   case model
   when User
       can [:read, :edit] , :all
   when Admin
       can :manage, :all
   else
       can :read, :all
   end
end

end

@giniedp

this is because the method "current_user" from devise would return only the user resource. Cancan uses that method to create an ability. So you have to override the current_ability method. My looks like this:

def current_auth_resource
  if admin_signed_in?
    current_admin
  else
    current_user
  end
end

def current_ability
    @current_ability or @current_ability = Ability.new(current_auth_resource)
end
@zooshme

Thank you giniedp. I'm quite new to RoR. In which file would I do this? In the Ability model? Could you please give me an example that includes also permission definitions?

@zooshme

Thank you. I've figured it out. In the ApplicationController. Thank you so much for your help.

@zooshme zooshme closed this Jun 19, 2012
@giniedp

i add both methods, the "current_auth_resource" and "current_ability" in my ApplicationHelper, that is included by the ApplicationController. So the methods are available for all controllers. Here is a sample

class ApplicationHelper
  def current_auth_resource
    if admin_signed_in?
      current_admin
    else
      current_user
    end
  end

  def current_ability
      @current_ability or @current_ability = Ability.new(current_auth_resource)
  end
end

class ApplicationController
  include ApplicationHelper
end

class Ability
  include CanCan::Ability

  def initialize(user)      
    if user.is_a?(Admin)
      # add admin permissions only
    elsif user.is_a?(User)
      # add user permissions only
    else
      # add guest permissions only
    end
  end
end
@zooshme

This looks nice and clean. Thank you.

@mikepack
Collaborator

@myresearchstyle This may be a nice resource for you to learn more about what's happening: http://mikepackdev.com/blog_posts/12-managing-devise-s-current-user-current-admin-and-current-troll-with-cancan

@zooshme
@icyflame

👍

This is really useful! Thanks @giniedp !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment