Odkazy:
Příklad 47.36. environment.rb
Rails::Initailizer.run do |config| … config.gem "declarative_authorization", :source => "http://gemcutter.org" …
$
rake gems:install
Vytvoříme si soubor config/authorization_rules.rb
authorization do role :admin do has_persmission_on [:articles, :comments], :to => [:index, :show, :new, :create, :edit, :update, :destroy] end end
V příslušném datovém modelu pak
# File: app/models/user.rb class User < ActiveRecord::Base acts_as_authentic # Použit gem authentic … has_many :roles, :through => :assignemnts def role_symbols # [:admin] if admin? roles.map do |role| role.name.underscore.to_sym end end end
class ApplicationController < ActionController::Base include Authentication helper :all protect_from_frogery before_filter {|c| Authorization.current_user = c.current_user} end
class ArticlesController < ApplicationController filter_resource_access end
# File: config/authorization_rules.rb
authorization do
role :admin do
has_persmission_on [:articles, :comments], :to => [:index, :show, :new, :create, :edit, :update, :destroy]
end
role :quest do
has_persmission_on :articles, :to => [:index, :show]
has_persmission_on :comments, :to => [:new, :create]
end
end
Změny v pohledu
# File: .../show.html.erb … <% if permitted_to? :edit, @article %> <%= link_to "Edit", edit_article_path(@article) %> <% end %> …
# File: config/authorization_rules.rb
…
role :quest do
has_persmission_on :articles, :to => [:index, :show]
has_persmission_on :comments, :to => [:new, :create]
has_persmission_on :comments, :to => [:edit, :update] do
if_attribute :user => is { user }
end
end
…
# File: .../application_controller.rb
class ApplicationController < ActionController::Base
include Authentication
helper :all
protect_from_frogery
before_filter {|c| Authorization.current_user = c.current_user}
protected
def permission_denied
flash[:error] = "Litujeme, ale nemáte oprávnění přístupu k té stránce."
redirect_ro root_url
end
end