
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?
Subscribe 
Follow us on
Twitter 
Archives
February 2012January 2012
December 2011
November 2011
October 2011
September 2011
August 2011
July 2011
May 2011
April 2011
March 2011
February 2011
January 2011
December 2010
November 2010
October 2010
September 2010
August 2010
July 2010
June 2010
May 2010
April 2010
March 2010
February 2010
January 2010
December 2009
November 2009
October 2009
September 2009
June 2009
March 2009
January 2009
December 2008
November 2008
September 2008
August 2008









Comments
Solution for your question is to put something alike to controller:
authorize_resource :class => false
you can also use symbol
---ability
can :read, :report
---controller
authorize! :index, :report
(use this inside the action)
OU
authorize_resource :class => false
(it call authorize for each action)
Add a Comment