RailsCasts - Ruby on Rails Screencasts

RailsCasts Pro episodes are now free!

Learn more or hide this

Declarative Authorization

#188 Declarative Authorization

Nov 16, 2009 | 15 minutes | Administration, Plugins, Authorization
Declarative authorization provides an advanced and powerful solution for role based authorization.
Click to Play Video ▶
Tweet
  • Download:
  • source code Project Files in Zip (106 KB)
  • mp4 Full Size H.264 Video (26.3 MB)
  • m4v Smaller H.264 Video (17.3 MB)
  • webm Full Size VP8 Video (45.3 MB)
  • ogv Full Size Theora Video (38.4 MB)
Browse_code Browse Source Code

Resources

bash
sudo rake gems:install
config/environment.rb
config.gem "declarative_authorization", :source => "http://gemcutter.org"
config/authorization_rules.rb
authorization do
 role :admin do
 has_permission_on [:articles, :comments], :to => [:index, :show, :new, :create, :edit, :update, :destroy]
 end
 
 role :guest do
 has_permission_on :articles, :to => [:index, :show]
 has_permission_on :comments, :to => [:new, :create]
 has_permission_on :comments, :to => [:edit, :update] do
 if_attribute :user => is { user }
 end
 end
 
 role :moderator do
 includes :guest
 has_permission_on :comments, :to => [:edit, :update]
 end
 
 role :author do
 includes :guest
 has_permission_on :articles, :to => [:new, :create]
 has_permission_on :articles, :to => [:edit, :update] do
 if_attribute :user => is { user }
 end
 end
end
application_controller.rb
before_filter { |c| Authorization.current_user = c.current_user }
protected
def permission_denied
 flash[:error] = "Sorry, you are not allowed to access that page."
 redirect_to root_url
end
articles_controller.rb
filter_resource_access
models/user.rb
has_many :assignments
has_many :roles, :through => :assignments
def role_symbols
 roles.map do |role|
 role.name.underscore.to_sym
 end
end
articles/show.html.erb
<p>
 <% if permitted_to? :edit, @article %>
 <%= link_to "Edit", edit_article_path(@article) %> |
 <% end %>
 <% if permitted_to? :destroy, @article %>
 <%= link_to "Destroy", @article, :method => :delete, :confirm => "Are you sure?" %> |
 <% end %>
 <%= link_to "Back to Articles", articles_path %>
</p>
...
<p>
 <% if permitted_to? :edit, comment %>
 <%= link_to "Edit", edit_comment_path(comment) %>
 <% end %>
 <% if permitted_to? :destroy, comment %>
 | <%= link_to "Destroy", comment, :method => :delete, :confirm => "Are you sure?" %>
 <% end %>
</p>
articles/index.html.erb
<% if permitted_to? :create, Article.new %>
 <p><%= link_to "New Article", new_article_path %></p>
<% end %>
loading

AltStyle によって変換されたページ (->オリジナル) /