Skip to content

Instantly share code, notes, and snippets.

@paulgroves
Created June 2, 2015 17:14
Show Gist options
  • Save paulgroves/778812c4974b23edb4a3 to your computer and use it in GitHub Desktop.
Save paulgroves/778812c4974b23edb4a3 to your computer and use it in GitHub Desktop.
Role auth
module RoleAuthentication
extend ActiveSupport::Concern
included do
append_before_filter :authorize_action
end
module ClassMethods
[:allow, :deny].each do |auth_action|
define_method "#{auth_action}_roles" do |roles, *args|
roles = [roles] unless roles.is_a? Array
self.class_eval do
prepend_before_filter -> { edit_roles roles, auth_action }, *args
end
end
end
end
private
def edit_roles(roles, action)
init_roles
case action
when :allow
@allowed_roles |= (roles & Roles::ALL)
when :deny
@denied_roles |= (roles & Roles::ALL)
end
end
def authorize_action
init_roles
valid_roles = @allowed_roles - @denied_roles
Rails.logger.debug("AUTHORIZED ROLES FOR #{self.controller_name}##{self.action_name}: #{valid_roles}")
deny_access unless valid_roles.any? && valid_roles.any?{ |r| current_user.send("is_#{r}") }
end
def init_roles
@allowed_roles ||= []
@denied_roles ||= []
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment