
On the Floor
A common problem when developing a web application is access control. A great, tidy solution I've found for this when building applications in Rails is CanCan. Rather than spreading permissions and access control logic throughout the application, CanCan centralizes permissions to a single class which gets initialized in the context of the current user and the item being accessed.
Installing CanCan
CanCan is available as a gem, so gem install cancan will do the trick. Be sure to include
in your environment.rb. You also need to have AuthLogic (or some other authentication scheme which gives you current_user) installed for this to work.
Defining your permissions Using Cancan
All of the permissions are stored in the Ability class -- you simply state which users can do what with what.
You get a user object containing the current_user, which can have roles associated with it. You can then do model specific tests to determine if the user has access to the item.
You simply include load_and_authorize_resource in the controller of the model you want restricted. In this case, my model is called Level.
This method will automagically populate a @level variable for your methods (new, edit, show, etc..) which has been run through the Ability class testing for permissions.
Testing permissions in views
In your views, you can test access to a resource by simply:
Potential Limitations
The only hiccup I've found in using CanCan to lock down access to resources is in the case when there is no model associated with a controller, such as a reports controller. A simple workaround I found was to create a dummy report.rb model in the models folder, which causes CanCan to pick up on it. Does anyone have any other solutions/workarounds for this issue?











Comments
Add a Comment