Created
August 6, 2013 18:53
-
-
Save pier-oliviert/6167471 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApplicationController < ActionController::Base | |
protect_from_forgery | |
prepend_before_filter :authenticate! | |
before_filter :restrict_routes! | |
cattr_accessor :skipping_authentication | |
rescue_from Exits::Unauthorized do |exception| | |
flash.alert = t("restrictions.unauthorized") | |
redirect_to :root and return | |
end | |
def self.allow(kls, *actions) | |
self.restrictions.add self, kls, actions | |
end | |
def self.restrictions | |
@@restrictions ||= Exits.new | |
end | |
protected | |
def restrict_routes! | |
return if self.class.restrictions.authorized?(self.class, current_user.class, action_name) | |
restricted! | |
end | |
def allow!(kls, &block) | |
return unless current_user.instance_of?(kls) | |
unless yield | |
restricted! | |
end | |
end | |
def restricted! | |
raise Exits::Unauthorized | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Exits | |
def initialize | |
@controllers = Hash.new | |
end | |
def add(controller_class, klass, *actions) | |
@controllers[controller_class] ||= Hash.new | |
@controllers[controller_class][klass] = actions.flatten | |
end | |
def authorized?(controller_class, klass, action) | |
controller = @controllers.fetch(controller_class, {}) | |
return true if controller.blank? | |
available_actions = controller.fetch(klass, []) | |
return true if available_actions.blank? || available_actions.include?(:all) | |
available_actions.include?(action.to_sym) | |
end | |
class Unauthorized < StandardError; end; | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyController < ApplicationController::Base | |
allow Admin, :all | |
allow User, :show, :edit | |
def edit | |
@user = User.find params[:id].to_i | |
allow! User do | |
current_user.eql? @user | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment