Permissions
User and Roles
Spree by default comes with admin
and user
roles. You can create more roles in the Admin Panel UI or rails console / seed, eg.:
Same with assigning a role, you can do it in the Admin Panel or from the console:
Ability class
For authorization Spree uses CanCanCan library. The main ability class by default is Spree::Ability.
Adding custom permissions
Let’s assume you would like to add a new Role customer_service
with some limited access to Admin Panel (only Orders section).
Create a new file called app/models/customer_service_ability.rb
Please familiarize yourself with CanCanCan syntax to understand can/cannot
methods more.
Now we need to inform Spree to use this ability, create another file app/models/spree/ability_decorator.rb
with contents:
Replacing all permissions
As we’ve mentioned earlier, Spree uses the main Ability class. You can change that to use your own custom Ability class via Dependencies in Spree initializer (config/initializers/spree.rb
), eg.
Now, let’s define that new class in app/models/custom_ability.rb
After restarting the rails server you observe new permissions being recognized in the application.
Further permission changes should be automatically picked up in development and should not require application restarts.