rails-doorman

rails-doorman is an authorization plugin for Ruby on Rails applications. This code was orignally written by Michael D. Ivey for Merb.

Configuration

Doorman expects the controller to respond to current_user

The :role option expects current_user to respond to has_role?(role_name). To change the default assign the option a new value:

Doorman.options[:has_role_method]

The :user option expects current_user to respond to login. To change the default assign the option a new value:

Doorman.options[:user_identifier_method]

Usage

Controllers

class Admin::ArticlesController < AdminController
  allow :role => :admin
end

allow :role => :admin                         # current_user.has_role?(:admin)
deny :role => :troll 
allow :role => :admin, :exclude => :show
allow :role => :troll, :only => :index

rails-doorman supports more than roles.

allow :user => :nancy                     # current_user.login.to_sym == 'nancy'.to_sym
allow :host => 'allowed.example.org'      # request.host =~ Regexp.new('allowed.example.org')
deny :host => 'denied.example.org'
deny :user_agent => /MSIE/                # request.user_agent =~ Regexp.new(/MSIE/)

Views

All rules can be used in views.

<% allow(:role => :admin) do %>
  <h1>Allowed</h1>
<% end %>

<% deny(:role => :troll) do %>
  <h1>Allowed</h1>
<% end %>

Unauthorized

When a rule fails a Doorman::Unauthorized error is raised. The error can be caught in ApplicationController#rescue_action_in_public.

class ApplicationController < ActionController::Base
  private
  def rescue_action_in_public(exception)
    case exception
    when Doorman::InvalidRule
      render :text => 'Invalid Rule', :status => '500 Internal Server Error'
    when Doorman::Unauthorized
      render :text => 'Unauthorized', :status => '401 Unauthorized'
    else
      super(exception)
    end
  end
end

Resources

Development

Source

  • git://github.com/jrun/rails-doorman.git

Bugs

TODO

Rule inheritance

Controller subclasses do not inherit its parents rules. This is more like a bug than a todo.

More configurable

rails-doorman should be configurable but in what ways?