Authorizr
A General purpose authorization framework.
Now sporting:
-
Controller level, block based authorization of resources and actions
-
Out of the box whitelist approach
-
Easy debugging of authorization actions with logger output
Implementing:
Simply add one line to your application controller to authorize all requests for all controllers:
app/controllers/application_controller.rb:
class ApplicationController < ActionController::Base
protect_from_forgery
end
Then in your controllers define an authorize block. Simply return true if the user is authorized to view the resoure and false if not. The block takes one parameter, the environment.
Examples:
app/controllers/posts_controller.rb:
#Example 1, deny everything always
do |env|
false
end
#Example 2, approve everything always
do |env|
true
end
#Example 3, approve index, show, create, new actions for everyone
# => and edit, update, destroy actions for the owner
do |env|
case env[:action]
when :index, :show, :create, :new
true
when :edit, :update, :destroy
post = Post.find env[:params][:id]
post.owner == current_user
else
false
end
end
#Example 4 [Advanced], Example 3 rewritten to use preloaded resource with user hook in place
do |env|
case env[:action]
when :index, :show, :create, :new
true
when :edit, :update, :destroy
env[:resource].user == env[:user]
else
false
end
end
Full detail on the environment passed into the authorize block:
env = {
:user => current_user, #nil unless ApplicationController responds to current_user
:action => self.action_name, #
:controller => self, #
:params => params, #
:resource => resource, # RESTful actions will attempt to fill this with your resource
:model => model #
}
License
This code is released under The MIT License (MIT) Copyright © 2011 Robert L Carpenter
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.