Created
June 26, 2013 16:43
-
-
Save pier-oliviert/5869093 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 | |
| before_filter :authenticate_user! | |
| before_filter :restrict_routes! | |
| cattr_reader :restrictions | |
| def self.allow(kls, *actions) | |
| @@restrictions ||= Restrictions.new | |
| self.restrictions.add self, kls, actions | |
| end | |
| protected | |
| def restrict_routes! | |
| return if self.restrictions.nil? | |
| return if self.restrictions.authorized?(self.class, current_user.class, action_name) | |
| restricted! | |
| end | |
| def allow!(kls, &block) | |
| return unless current_user.instance_of?(kls) | |
| unless block.call | |
| restricted! | |
| end | |
| end | |
| def restricted! | |
| flash.notice = "You are not authorized" | |
| redirect_to :root and return | |
| end | |
| end | |
| class Restrictions | |
| 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?(action.to_sym) | |
| 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
| module ApplicationHelper | |
| def can?(controller, action) | |
| controller.restrictions.authorized? controller, current_user.class, action | |
| 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 UsersController < ApplicationController | |
| allow User, :show, :edit, :update | |
| allow Admin, :all | |
| def edit | |
| 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