Guest User

Untitled

a guest
Jul 18th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.91 KB | None | 0 0
  1. module YawmaAccessSystem # simple variation of acl system
  2. def self.included(subject)
  3. subject.extend(ClassMethods)
  4. if subject.respond_to? :helper_method
  5. subject.helper_method(:is_allowed_to?)
  6. end
  7. end
  8. protected
  9.  
  10. module ClassMethods
  11. # yawma_access_control [:create, :edit] => 'administrator & !company',
  12. # :update => 'administrator',
  13. # :list => 'company | band'
  14. def yawma_access_control(actions={})
  15. # Add class-wide permission callback to before_filter
  16. defaults = {}
  17. if block_given?
  18. yield defaults
  19. default_block_given = true
  20. end
  21. before_filter do |c|
  22. c.default_access_context = defaults if default_block_given
  23.  
  24. access = actions.inject({}) do |auth, current|
  25. [current.first].flatten.each { |action| auth[action] = current.last }
  26. auth
  27. end
  28.  
  29. allowed = if access.has_key?(c.action_name.to_sym)
  30. logic_parse(access[c.action_name.to_sym].dup, c.send(:current_user))
  31. elsif access.has_key? :DEFAULT
  32. logic_parse(access[:DEFAULT].dup, c.send(:current_user))
  33. else
  34. true
  35. end
  36.  
  37. if allowed
  38. true
  39. else
  40. if c.respond_to?(:permission_denied)
  41. c.send(:permission_denied)
  42. else
  43. c.send(:render, :text => "You have insuffient permissions to access #{c.controller_name}/#{c.action_name}")
  44. end
  45. end
  46. end
  47. end
  48.  
  49. def logic_parse(expression, context)
  50. while expression =~ /\(/
  51. expression.sub!(/\(([^\)]+)\)/) {
  52. logic_parse($1, context)
  53. }
  54. end
  55.  
  56. # process each operator in order of precedence
  57. #!
  58. while expression =~ /!/
  59. expression.sub!(/!([^ &|]+)/) {
  60. (!check(expression[$1], context)).to_s
  61. }
  62. end
  63.  
  64. #&
  65. if expression =~ /&/
  66. return (logic_parse(expression[/^[^&]+/], context) and logic_parse(expression[/^[^&]+&(.*)$/,1], context))
  67. end
  68.  
  69. #|
  70. if expression =~ /\|/
  71. return (logic_parse(expression[/^[^\|]+/], context) or logic_parse(expression[/^[^\|]+\|(.*)$/,1], context))
  72. end
  73.  
  74. # constants
  75. if expression =~ /^\s*true\s*$/i
  76. return true
  77. elsif expression =~ /^\s*false\s*$/i
  78. return false
  79. end
  80.  
  81. # single list items
  82. (check(expression.strip, context))
  83. end
  84.  
  85. def check(key, current_user)
  86. current_user.userable.user_type == key
  87. end
  88. end
  89.  
  90. # if is_allowed_to?('company|band')
  91. # do something
  92. # end
  93. def is_allowed_to?( logicstring )
  94. # logic_parse(logicstring, current_user)
  95. roles = logicstring.split('|')
  96. roles.include?( current_user.userable.user_type )
  97. end
  98. end
Add Comment
Please, Sign In to add comment