# module RoleBasedSecurity module ControllerAdditions # ::Rails.logger.error("...") # Hook to extend def self.included(klass) klass.send :class_inheritable_array, :role_requirements klass.send :role_requirements=, [] end module ClassMethods # Add this to the top of your controller to require a role in order to access it. # Example Usage: # # require_role "contractor" # require_role "admin", :only => :destroy # don't allow contractors to destroy # require_role "admin", :only => :update, :unless => "current_<%= users_name %>.authorized_for_listing?(params[:id]) " # # Valid options # # * :only - Only require the role for the given actions # * :except - Require the role for everything but # * :if - a Proc or a string to evaluate. If it evaluates to true, the role is required. # * :unless - The inverse of :if # def require_role(roles, options = {}) options.assert_valid_keys(:if, :unless, :for, :only, :for_all_except, :except ) # only declare that before filter once unless (@before_filter_declared||=false) @before_filter_declared=true before_filter :check_roles end # convert to an array if it isn't already roles = [roles] unless Array===roles options[:only] ||= options[:for] if options[:for] options[:except] ||= options[:for_all_except] if options[:for_all_except] # convert any actions into symbols for key in [:only, :except] if options.has_key?(key) options[key] = [options[key]] unless Array === options[key] options[key] = options[key].compact.collect{|v| v.to_sym} end end self.role_requirements||=[] self.role_requirements << {:roles => roles, :options => options } end end # Before filter to check roles # current_user come from authlogic # self.role_requirements = [{:roles=>["admin"], :options=>{}}] def check_roles return true if self.role_requirements.size() == 0 if !current_user.nil? self.role_requirements.each do |role_requirement| role_requirement[:roles].each do |role| return true if current_user.has_role?(role) end end end # # Set flash and redurn to main page flash[:warning] = I18n.t ::RoleBasedSecurity.options[:locale_message_key], :default => ::RoleBasedSecurity.options[:invalid_rights_message] redirect_to(::RoleBasedSecurity.options[:home_path]) false end end end