Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CanCan: limiting a user's ability to set certain model attributes based on their role

Tags:

I have a Post model with a :published attribute (boolean) and a User model with a role attribute (string). There are three roles: ROLES = %w[admin publisher author]

I don't want users whose role is author to be capable of setting, or editing, the :published field on the Post model.

I'm using CanCan (and RailsAdmin gem) and my simplified Ability.rb file looks like this:

class Ability
  include CanCan::Ability
  def initialize(user)
    user ||= User.new

    if user.role? :admin
      can :manage, :all
    elsif user.role? :publisher
      can :manage, Post
    elsif user.role? :author
      # I want to prevent these guys from setting the :published attribute
    end

  end
end

Anyone got any tips for doing this sort of thing?

like image 505
stephenmurdoch Avatar asked May 07 '11 14:05

stephenmurdoch


2 Answers

So far it is not possible. But according to this: https://github.com/ryanb/cancan/issues/326 this feature should be in cancan 2.0.

Update: you can see this on CanCan 2.0 branch here: https://github.com/ryanb/cancan/tree/2.0 in section "Resource Attributes"

like image 197
Piotrek Okoński Avatar answered Oct 06 '22 00:10

Piotrek Okoński


Check out this post: How do I use CanCan with rails admin to check for ownership

It shows how to make a field not visible based off a users role.

UPDATE I was able to set options in rails admin with this code:

config.model User do
  edit do
    configure :organization do
      visible do
        bindings[:view]._current_user.max_role_name != 'admin' ? false : true
      end
    end

    configure :organization_id, :hidden do
      visible do
        true if bindings[:view]._current_user.max_role_name != 'admin'
      end
      default_value do
        bindings[:view]._current_user.organization_id if bindings[:view]._current_user.max_role_name != 'admin'
      end
    end

    include_all_fields
  end
end

This configuration will hide the organization field if the logged in user is not an admin. It will then show an organization_id field ( set to type='hidden' ) and set the default value.

Hope this helps someone.

like image 30
John Goodman Avatar answered Oct 06 '22 01:10

John Goodman