David - Musings of an SRE

10 Steps to getting role authorization working on your rails project

How to get declarative_authorization working on a brand new rails project in 10 steps

1) In your config/environment.rb, Add the line
config.gem "declarative_authorization", :source => "http://gemcutter.org"

2) Do a rake gems:install

3) Create a Role model

./script/generate model Role title:name

4) In your migration file that comes with your model, reference the role table with your user model (replace the name of the model as necessary)

t.references :user

5) In your User model, create a has_many :roles association

6) In your Role model, create a belongs_to association

7) Create a authorization file that will contain your authorization file. in config/authorization_rules.rb
authorization do   role :admin do     has_permission_on :controller_or_model, :to => :method   end end

8. Set the role_symbols in your User model. Add the following method:

def role_symbols   (roles || []).map {|r| r.title.to_sym} end

9. rake db:migrate

10. Assign roles to your User by @user.roles.create(:title => 'admin') and you're done!

Bonus

11. Add "filter_access_to :all" in all your controllers that needs the authorization check

12. You'd need to set your current_user to Authorization. If you're using Authlogic, you can do the following in your ApplicationController

Add the following code near the top ...

  before_filter :set_current_user

  def set_current_user     Authorization.current_user = current_user   end

13. To have Declarative Authorization send a custom message and/or redirection upon user accessing a controller/model without proper authorization, in the same ApplicationController, add the following public method

def permission_denied   flash[:error] = “You shouldn’t be here! hmmpft!”   redirect_to “/” end