Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module YawmaAccessSystem # simple variation of acl system
- def self.included(subject)
- subject.extend(ClassMethods)
- if subject.respond_to? :helper_method
- subject.helper_method(:is_allowed_to?)
- end
- end
- protected
- module ClassMethods
- # yawma_access_control [:create, :edit] => 'administrator & !company',
- # :update => 'administrator',
- # :list => 'company | band'
- def yawma_access_control(actions={})
- # Add class-wide permission callback to before_filter
- defaults = {}
- if block_given?
- yield defaults
- default_block_given = true
- end
- before_filter do |c|
- c.default_access_context = defaults if default_block_given
- access = actions.inject({}) do |auth, current|
- [current.first].flatten.each { |action| auth[action] = current.last }
- auth
- end
- allowed = if access.has_key?(c.action_name.to_sym)
- logic_parse(access[c.action_name.to_sym].dup, c.send(:current_user))
- elsif access.has_key? :DEFAULT
- logic_parse(access[:DEFAULT].dup, c.send(:current_user))
- else
- true
- end
- if allowed
- true
- else
- if c.respond_to?(:permission_denied)
- c.send(:permission_denied)
- else
- c.send(:render, :text => "You have insuffient permissions to access #{c.controller_name}/#{c.action_name}")
- end
- end
- end
- end
- def logic_parse(expression, context)
- while expression =~ /\(/
- expression.sub!(/\(([^\)]+)\)/) {
- logic_parse($1, context)
- }
- end
- # process each operator in order of precedence
- #!
- while expression =~ /!/
- expression.sub!(/!([^ &|]+)/) {
- (!check(expression[$1], context)).to_s
- }
- end
- #&
- if expression =~ /&/
- return (logic_parse(expression[/^[^&]+/], context) and logic_parse(expression[/^[^&]+&(.*)$/,1], context))
- end
- #|
- if expression =~ /\|/
- return (logic_parse(expression[/^[^\|]+/], context) or logic_parse(expression[/^[^\|]+\|(.*)$/,1], context))
- end
- # constants
- if expression =~ /^\s*true\s*$/i
- return true
- elsif expression =~ /^\s*false\s*$/i
- return false
- end
- # single list items
- (check(expression.strip, context))
- end
- def check(key, current_user)
- current_user.userable.user_type == key
- end
- end
- # if is_allowed_to?('company|band')
- # do something
- # end
- def is_allowed_to?( logicstring )
- # logic_parse(logicstring, current_user)
- roles = logicstring.split('|')
- roles.include?( current_user.userable.user_type )
- end
- end
Add Comment
Please, Sign In to add comment