Access Control in Rails

December 10th, 2006

You need to install the acl2 plugin from

http://opensvn.csie.org/ezra/rails/plugins/dev/acl_system2/

 

Here is an example of its use.  the access_control is thanks to this plugin

 

class PostController < ApplicationController
  before_filter :login_required, :except => [:list, :index]
  access_control [:new, :create, :update, :edit] => ‘(admin | user | moderator)’,
                 :delete => ‘admin & (!moderator & !blacklist)’ 
There are two callback methods you can use to define your own success and failure behaviors. If you define permission_granted and/or permission_denied as protected methods in your controller you can redirect or render and error page or whatever else you might want to do if access is allowed or denied. 

 

  # the rest of your controller here

  protected

  def permission_denied
    flash[:notice] = “You don’t have privileges to access this action”
    return redirect_to :action => ‘denied’
  end

  def permission_granted
    flash[:notice] = “Welcome to the secure area of foo.com!”
  end
There is also a helper method that can be used in the view or controller. In the view its handy for conditional menus or stuff like that.

   
So here is the schema of this application including the Post model and the User and Role model plus the habtm join table:
ActiveRecord::Schema.define(:version => 3) do
create_table "roles", :force => true do |t|
t.column "title", :string
end
create_table "roles_users", :id => false, :force => true do |t|
t.column "role_id", :integer
t.column "user_id", :integer
end
create_table "users", :force => true do |t|
t.column "login", :string, :limit => 40
t.column "email", :string, :limit => 100
t.column "crypted_password", :string, :limit => 40
t.column "salt", :string, :limit => 40
t.column "created_at", :datetime
t.column "updated_at", :datetime
end
end  

 

installing acts_as_authenticated

December 9th, 2006

Setting up local gem repository

December 8th, 2006

Using has_many with STI

December 7th, 2006