hierarchical user authorisation in rails using cancan
13 Mar 2012
Assume that we need a web application that should have users with different roles. Furthermore let’s say we need these roles
to be hierarchic in other word suppose we have Admin, Manager, Seller, Buyer and Reporter roles.
Admin can do everything that Manager, Seller, Buyer can, Manager can do everything that Seller and Buyer can. Seller, Buyer and Reporter
are the last elements of this hierarchy.
So there is an hierarchy between roles. Lets implement this authorisation system.
I will use Mongoid ODM in my models. First we need to create User model as follows:
Now let’s define Role model
Defining User model and Role model in this way will allow us to make role hierarchical. That is, in the console we can try following:
Before trying in console create sample models and users.
Now we have general relationship logic between roles that can be used either for creation hierarchical or non hierarchical roles.
It is time to create abilities. I suppose you can use CanCan. First we need to create Ability model to define abilities.
To do this CanCan has generator like this: rails g cancan:ability. After running this command edit the Ability model and define abilities
according to your application’s business logic. Some samples:
In this case because of we have hierarchy so that admin is also manager admin will be able to read, update Product, manager User and Report.
But reporter wil only be able to manage reports.