Access Control in Rails
December 10th, 2006You 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) docreate_table "roles", :force => true do |t|t.column "title", :stringendcreate_table "roles_users", :id => false, :force => true do |t|t.column "role_id", :integert.column "user_id", :integerendcreate_table "users", :force => true do |t|t.column "login", :string, :limit => 40t.column "email", :string, :limit => 100t.column "crypted_password", :string, :limit => 40t.column "salt", :string, :limit => 40t.column "created_at", :datetimet.column "updated_at", :datetimeendend