Respec’ my Authoritah!!

A stupidly simple authorization gem for Rails.

Installation

Make sure Gemcutter is in your repo sources:

$ gem sources -a http://gems.gemcutter.org

Installation:

$ sudo gem install authoritah

Usage

By default (i.e. when no Authoritah declarations are made) all requests are allowed. Authoritah is pretty flexible in introducing authorization rules to your application. An example is called for:

class WidgetController < ApplicationController

  permits :current_user => :admin?
end

This is a wildcard rule. It assumes you have a method on your controller called “current_user” (as something like restful_authentication or authlogic would provide) that returns an object that can respond to an admin? message - the rule will pass if admin? returns true (or more strictly, non-false). Once a permit rule is defined access to the actions of this controller are ONLY permitted if you fulfill the predicate. If you just have a case where you have a method on your controller to check authorisation, you can do the following:

class WidgetController < ApplicationController

  permits :logged_in?
end

What about if we only want to control access to certain actions? Easy, add a :to option and pass it an action or array of actions. You can add as many rules and scope them by action - Authoritah will ensure that a request is only permitted if all rules for a given action pass.

class WidgetController < ApplicationController

  permits :current_user => :admin?, :to => [:create, :destroy]
  permits :current_user => :logged_in?, :to => :show
end

You also have the ability to expressly forbid access using the forbids directive:

class WidgetController < ApplicationController

  permits :current_user => :logged_in?
  forbids :current_user => :blacklisted?, :from => [:create, :destroy]
end

In this scenario any logged in user can access the controller actions, but any user responding true to blacklisted? will be forbidden from running the :create or :destroy actions.

You can also pass a Proc as the predicate:

class WidgetController < ApplicationController

  forbids :current_user => Proc.new {|user| user.name.index("Hacky McHackster") }
end

The Proc gets passed the result of the :current_user message to the controller for you to specify more complex rules.

I’ve also now added the ability to customise how the user is using the :on_reject option. You can either pass it a symbol identifying a method to call, or a Proc:

class WidgetController < ApplicationController

  permits :current_user => :logged_in?, :on_reject => :redirect_to_login
  forbids :current_user => :blacklisted?, :from => [:create, :destroy], :on_reject => Proc.new { redirect_to '/blacklisted' }

  def 
    flash[:notice] = "Please login to view widgets"
    redirect_to root_url
  end
end