Zarne Dravitzki
Zarne Dravitzki

Reputation: 1688

Spree Custom Roles Permissions

I am trying to give some custom roles within spree specific permissions. Cant find this answer anywhere

role_ability.rb

class RoleAbility
 include CanCan::Ability

 def initialize(user)

 user || User.new # for guest

 if user.has_role? "admin"
   can :manage, :all
 elsif user.has_role? "retailer"
   can :manage, Product
 else
   can :read, :all
 end


 end
end

I thought this might be a popular idea, of letting a user with role 'manager' manage only products and other certain Models...

if I change

 elsif user.has_role? "retailer"
can :manage, Product

to

 elsif user.has_role? "retailer"
can :manage, :all

It works as expected... I can access all of the admin area

I only want the "Retailer" to be able to :manage Products tho!! ;)

"admin" is only a role associated with a user, ie all roles are Users.

You can probably see where this is going, Retailers can sign up and sell items of their own.. well thats the goal.

Any pointers??

Upvotes: 2

Views: 5441

Answers (2)

John Hirbour
John Hirbour

Reputation: 566

There is a native way in spree_auth_devise to do this. It was not documented, but now is.

https://github.com/spree/spree_auth_devise Section: "Using in an existing Rails application"

Upvotes: 2

complistic
complistic

Reputation: 2710

A quick fix to this problem would be to add a authorize_admin method to a Admin::ProductsController decorator.rb

app/controllers/admin_products_controller_decorator.rb

Admin::ProductsController.class_eval do
    def authorize_admin
        authorize! :admin, Product
        authorize! params[:action].to_sym, Product
    end
end

NOTE: This will override the one set in auth/app/controllers/admin_orders_controller_decorator.rb removing the ":admin, Object" requirement for this controller.

That means the role will have to have access to both the :admin AND :action for Product.. ie:

app/models/retailer_ability.rb

class RetailerAbility
  include CanCan::Ability

  def initialize(user)
    user ||= User.new
    if user.has_role? "retailer"
      can :read, Product
      can :admin, Product
    end
  end
end

Should allow retailers to read products on the admin.

Also Dont forget to add this to an initializer:

config/initializers/spree.rb

Ability.register_ability(RetailerAbility)

Upvotes: 4

Related Questions