Created
June 2, 2015 17:14
-
-
Save paulgroves/778812c4974b23edb4a3 to your computer and use it in GitHub Desktop.
Role auth
This file contains 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 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