Screencast: Authorisierung mit CanCan

Authorisierung in Webapplikation lassen sich auf einfache Art und Weise mit CanCan realisieren. Ryan Bates zeigt in diesem Screencast wie dieses Plugin eingesetzt werden kann.

 

Download (30.2 MB, 15:57)
Alternativer Download für iPod & Apple TV (20.3 MB, 15:57)

 

Resourcen:

Quellcode:

sudo rake gems:install
# config/environment.rb
config.gem "cancan"

# models/ability.rb
class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user

    if user.role? :admin
      can :manage, :all
    else
      can :read, :all
      can :create, Comment
      can :update, Comment do |comment|
        comment.try(:user) == user || user.role?(:moderator)
      end
      if user.role?(:author)
        can :create, Article
        can :update, Article do |article|
          article.try(:user) == user
        end
      end
    end
  end
end

# application_controller.rb
rescue_from CanCan::AccessDenied do |exception|
  flash[:error] = "Access denied."
  redirect_to root_url
end

# articles_controller.rb
load_and_authorize_resource

# comments_controller.rb possibility
load_and_authorize_resource :nested => :article
<!-- articles/show.html.erb -->
<p>
  <% if can? :update, @article %>
    <%= link_to "Edit", edit_article_path(@article) %> |
  <% end %>
  <% if can? :destroy, @article %>
    <%= link_to "Destroy", @article, :method => :delete, :confirm => "Are you sure?" %> |
  <% end %>
  <%= link_to "Back to Articles", articles_path %>
</p>
...
<p>
  <% if can? :update, comment %>
    <%= link_to "Edit", edit_comment_path(comment) %>
  <% end %>
  <% if can? :destroy, comment %>
    | <%= link_to "Destroy", comment, :method => :delete, :confirm => "Are you sure?" %>
  <% end %>
</p>

<!-- articles/index.html.erb -->
<% if can? :create, Article %>
  <p><%= link_to "New Article", new_article_path %></p>
<% end %>

Eingestellt am 14.12.2009 um 13:45

Kategorie: Tutorials

Be Sociable, Share!

Kommentare für diesen Artikel wurden geschlossen.

Suchen auf rubyonrails.de

Aktuelle Rails Version + Abhängigkeiten:

Gem rails-3.0.0
actionmailer (= 3.0.0, runtime)
actionpack (= 3.0.0, runtime)
activerecord (= 3.0.0, runtime)
activeresource (= 3.0.0, runtime)
activesupport (= 3.0.0, runtime)
bundler (~> 1.0.0, runtime)
railties (= 3.0.0, runtime)

Rails auf Rubyforge
Rails auf Github