How to use cancancan?
Asked Answered
G

3

5

I want to give rights to users in my rails app. I have 'admin' who can create, update and delete all posts and comments, 'user' who can create and update only his own comments, and 'guest' who can do none of these. For this I use the gems 'devise' and 'cancancan'. I understand the 'devise' gem, but I don't understand 'cancancan'.

In the class ability.rb, how can I write rights for these users (admin, user, guest)?

Griceldagrid answered 8/12, 2014 at 11:33 Comment(0)
E
6

Cancancan lets you only define permissions for given context. This context might be a user role which is not a part of cancancan and hence roles have to be defined by yourself.

There are various ways to define user role, e.g.

  • as a Role model,
  • Rails enum,
  • as suggested here,
  • as a string attribute of User model.

It all depends of the use case. An example of how to define abilities can be found here. In your case, it would look like:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new

    if user.reviewer? #Just a logged user
      can :manage, Comment, { owner_id: user.id }
    elsif user.admin?
      can :manage, :all
    end
  end
end

class User < ActiveRecord::Base
  enum role: [ :reviewer, :admin ]
end
Eutrophic answered 8/12, 2014 at 11:52 Comment(0)
M
1

You can refer following rails cast http://railscasts.com/episodes/192-authorization-with-cancan

Macule answered 8/12, 2014 at 11:48 Comment(0)
M
0

If you are going to use Roles, consider the Canard gem (https://github.com/james2m/canard) which combines CanCanCan with RoleModel (https://github.com/martinrehfeld/role_model). This gives you a well organized way of stipulating roles and their abilities

For example, if you have a user model, you would set the roles as follows:

class User < ActiveRecord::Base
  acts_as_user roles: [:supervisor, :manager, :writer]
end

Then you can create Ability files for each role, including a base User (not assigned any roles) and Guest (not logged in)

Canard::Abilities.for(:user) do
  can  :manage, User, id: user.id
  cannot  [:destroy], User
end

The above will allow a user to update their own information but will not allow them to delete themselves. They also will not have access to any other user record.

Manchester answered 15/1, 2016 at 14:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.