Spree Custom Roles Permissions

本小妞迷上赌 提交于 2019-12-09 07:05:13

问题


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??


回答1:


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"




回答2:


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)


来源:https://stackoverflow.com/questions/5455174/spree-custom-roles-permissions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!