graylog2-declarative_authorization 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. data/CHANGELOG +153 -0
  2. data/MIT-LICENSE +20 -0
  3. data/README.rdoc +529 -0
  4. data/Rakefile +35 -0
  5. data/app/controllers/authorization_rules_controller.rb +259 -0
  6. data/app/controllers/authorization_usages_controller.rb +23 -0
  7. data/app/helpers/authorization_rules_helper.rb +218 -0
  8. data/app/views/authorization_rules/_change.erb +58 -0
  9. data/app/views/authorization_rules/_show_graph.erb +44 -0
  10. data/app/views/authorization_rules/_suggestions.erb +48 -0
  11. data/app/views/authorization_rules/change.html.erb +169 -0
  12. data/app/views/authorization_rules/graph.dot.erb +68 -0
  13. data/app/views/authorization_rules/graph.html.erb +47 -0
  14. data/app/views/authorization_rules/index.html.erb +17 -0
  15. data/app/views/authorization_usages/index.html.erb +36 -0
  16. data/authorization_rules.dist.rb +20 -0
  17. data/config/routes.rb +20 -0
  18. data/garlic_example.rb +20 -0
  19. data/init.rb +5 -0
  20. data/lib/declarative_authorization.rb +17 -0
  21. data/lib/declarative_authorization/authorization.rb +705 -0
  22. data/lib/declarative_authorization/development_support/analyzer.rb +252 -0
  23. data/lib/declarative_authorization/development_support/change_analyzer.rb +253 -0
  24. data/lib/declarative_authorization/development_support/change_supporter.rb +620 -0
  25. data/lib/declarative_authorization/development_support/development_support.rb +243 -0
  26. data/lib/declarative_authorization/helper.rb +68 -0
  27. data/lib/declarative_authorization/in_controller.rb +645 -0
  28. data/lib/declarative_authorization/in_model.rb +162 -0
  29. data/lib/declarative_authorization/maintenance.rb +212 -0
  30. data/lib/declarative_authorization/obligation_scope.rb +354 -0
  31. data/lib/declarative_authorization/rails_legacy.rb +22 -0
  32. data/lib/declarative_authorization/railsengine.rb +6 -0
  33. data/lib/declarative_authorization/reader.rb +521 -0
  34. data/lib/tasks/authorization_tasks.rake +82 -0
  35. data/test/authorization_test.rb +1104 -0
  36. data/test/controller_filter_resource_access_test.rb +511 -0
  37. data/test/controller_test.rb +480 -0
  38. data/test/dsl_reader_test.rb +178 -0
  39. data/test/helper_test.rb +247 -0
  40. data/test/maintenance_test.rb +46 -0
  41. data/test/model_test.rb +1883 -0
  42. data/test/schema.sql +55 -0
  43. data/test/test_helper.rb +152 -0
  44. metadata +112 -0
@@ -0,0 +1,243 @@
1
+
2
+ module Authorization
3
+ module DevelopmentSupport
4
+ class AbstractAnalyzer
5
+ attr_reader :engine
6
+
7
+ def initialize (engine)
8
+ @engine = engine
9
+ end
10
+
11
+ def roles
12
+ AnalyzerEngine.roles(engine)
13
+ end
14
+
15
+ def rules
16
+ roles.collect {|role| role.rules }.flatten
17
+ end
18
+ end
19
+
20
+ # Groups utility methods and classes to better work with authorization object
21
+ # model.
22
+ module AnalyzerEngine
23
+
24
+ def self.roles (engine)
25
+ Role.all(engine)
26
+ end
27
+
28
+ def self.relevant_roles (engine, users)
29
+ users.collect {|user| user.role_symbols.map {|role_sym| Role.for_sym(role_sym, engine)}}.
30
+ flatten.uniq.collect {|role| [role] + role.ancestors}.flatten.uniq
31
+ end
32
+
33
+ def self.rule_for_permission (engine, privilege, context, role)
34
+ AnalyzerEngine.roles(engine).
35
+ find {|cloned_role| cloned_role.to_sym == role.to_sym}.rules.find do |rule|
36
+ rule.contexts.include?(context) and rule.privileges.include?(privilege)
37
+ end
38
+ end
39
+
40
+ def self.apply_change (engine, change)
41
+ case change[0]
42
+ when :add_role
43
+ role_symbol = change[1]
44
+ if engine.roles.include?(role_symbol)
45
+ false
46
+ else
47
+ engine.roles << role_symbol
48
+ true
49
+ end
50
+ when :add_privilege
51
+ privilege, context, role = change[1,3]
52
+ role = Role.for_sym(role.to_sym, engine)
53
+ privilege = Privilege.for_sym(privilege.to_sym, engine)
54
+ if ([privilege] + privilege.ancestors).any? {|ancestor_privilege| ([role] + role.ancestors).any? {|ancestor_role| !ancestor_role.rules_for_permission(ancestor_privilege, context).empty?}}
55
+ false
56
+ else
57
+ engine.auth_rules << AuthorizationRule.new(role.to_sym,
58
+ [privilege.to_sym], [context])
59
+ true
60
+ end
61
+ when :remove_privilege
62
+ privilege, context, role = change[1,3]
63
+ role = Role.for_sym(role.to_sym, engine)
64
+ privilege = Privilege.for_sym(privilege.to_sym, engine)
65
+ rules_with_priv = role.rules_for_permission(privilege, context)
66
+ if rules_with_priv.empty?
67
+ false
68
+ else
69
+ rules_with_priv.each do |rule|
70
+ rule.rule.privileges.delete(privilege.to_sym)
71
+ engine.auth_rules.delete(rule.rule) if rule.rule.privileges.empty?
72
+ end
73
+ true
74
+ end
75
+ end
76
+ end
77
+
78
+ class Role
79
+ @@role_objects = {}
80
+ attr_reader :role
81
+ def initialize (role, rules, engine)
82
+ @role = role
83
+ @rules = rules
84
+ @engine = engine
85
+ end
86
+
87
+ def source_line
88
+ @rules.empty? ? nil : @rules.first.source_line
89
+ end
90
+ def source_file
91
+ @rules.empty? ? nil : @rules.first.source_file
92
+ end
93
+
94
+ # ancestors' privileges are included in in the current role
95
+ def ancestors (role_symbol = nil)
96
+ role_symbol ||= @role
97
+ (@engine.role_hierarchy[role_symbol] || []).
98
+ collect {|lower_role| ancestors(lower_role) }.flatten +
99
+ (role_symbol == @role ? [] : [Role.for_sym(role_symbol, @engine)])
100
+ end
101
+ def descendants (role_symbol = nil)
102
+ role_symbol ||= @role
103
+ (@engine.rev_role_hierarchy[role_symbol] || []).
104
+ collect {|higher_role| descendants(higher_role) }.flatten +
105
+ (role_symbol == @role ? [] : [Role.for_sym(role_symbol, @engine)])
106
+ end
107
+
108
+ def rules
109
+ @rules ||= @engine.auth_rules.select {|rule| rule.role == @role}.
110
+ collect {|rule| Rule.new(rule, @engine)}
111
+ end
112
+ def rules_for_permission (privilege, context)
113
+ rules.select do |rule|
114
+ rule.matches?([@role], [privilege.to_sym], context)
115
+ end
116
+ end
117
+
118
+ def to_sym
119
+ @role
120
+ end
121
+ def self.for_sym (role_sym, engine)
122
+ @@role_objects[[role_sym, engine]] ||= new(role_sym, nil, engine)
123
+ end
124
+
125
+ def self.all (engine)
126
+ rules_by_role = engine.auth_rules.inject({}) do |memo, rule|
127
+ memo[rule.role] ||= []
128
+ memo[rule.role] << rule
129
+ memo
130
+ end
131
+ engine.roles.collect do |role|
132
+ new(role, (rules_by_role[role] || []).
133
+ collect {|rule| Rule.new(rule, engine)}, engine)
134
+ end
135
+ end
136
+ def self.all_for_privilege (privilege, context, engine)
137
+ privilege = privilege.is_a?(Symbol) ? Privilege.for_sym(privilege, engine) : privilege
138
+ privilege_symbols = ([privilege] + privilege.ancestors).map(&:to_sym)
139
+ all(engine).select {|role| role.rules.any? {|rule| rule.matches?([role.to_sym], privilege_symbols, context)}}.
140
+ collect {|role| [role] + role.descendants}.flatten.uniq
141
+ end
142
+ end
143
+
144
+ class Rule
145
+ @@rule_objects = {}
146
+ delegate :source_line, :source_file, :contexts, :matches?, :to => :@rule
147
+ attr_reader :rule
148
+ def initialize (rule, engine)
149
+ @rule = rule
150
+ @engine = engine
151
+ end
152
+ def privileges
153
+ PrivilegesSet.new(self, @engine, @rule.privileges.collect {|privilege| Privilege.for_sym(privilege, @engine) })
154
+ end
155
+ def self.for_rule (rule, engine)
156
+ @@rule_objects[[rule, engine]] ||= new(rule, engine)
157
+ end
158
+ end
159
+
160
+ class Privilege
161
+ @@privilege_objects = {}
162
+ def initialize (privilege, engine)
163
+ @privilege = privilege
164
+ @engine = engine
165
+ end
166
+
167
+ # Ancestor privileges are higher in the hierarchy.
168
+ # Doesn't take context into account.
169
+ def ancestors (priv_symbol = nil)
170
+ priv_symbol ||= @privilege
171
+ # context-specific?
172
+ (@engine.rev_priv_hierarchy[[priv_symbol, nil]] || []).
173
+ collect {|higher_priv| ancestors(higher_priv) }.flatten +
174
+ (priv_symbol == @privilege ? [] : [Privilege.for_sym(priv_symbol, @engine)])
175
+ end
176
+ def descendants (priv_symbol = nil)
177
+ priv_symbol ||= @privilege
178
+ # context-specific?
179
+ (@engine.privilege_hierarchy[priv_symbol] || []).
180
+ collect {|lower_priv, context| descendants(lower_priv) }.flatten +
181
+ (priv_symbol == @privilege ? [] : [Privilege.for_sym(priv_symbol, @engine)])
182
+ end
183
+
184
+ def rules
185
+ @rules ||= find_rules_for_privilege
186
+ end
187
+ def source_line
188
+ rules.empty? ? nil : rules.first.source_line
189
+ end
190
+ def source_file
191
+ rules.empty? ? nil : rules.first.source_file
192
+ end
193
+
194
+ def to_sym
195
+ @privilege
196
+ end
197
+ def self.for_sym (privilege_sym, engine)
198
+ @@privilege_objects[[privilege_sym, engine]] ||= new(privilege_sym, engine)
199
+ end
200
+
201
+ private
202
+ def find_rules_for_privilege
203
+ @engine.auth_rules.select {|rule| rule.privileges.include?(@privilege)}.
204
+ collect {|rule| Rule.for_rule(rule, @engine)}
205
+ end
206
+ end
207
+
208
+ class PrivilegesSet < Set
209
+ def initialize (*args)
210
+ if args.length > 2
211
+ @rule = args.shift
212
+ @engine = args.shift
213
+ end
214
+ super(*args)
215
+ end
216
+ def include? (privilege)
217
+ if privilege.is_a?(Symbol)
218
+ super(privilege_from_symbol(privilege))
219
+ else
220
+ super
221
+ end
222
+ end
223
+ def delete (privilege)
224
+ @rule.rule.privileges.delete(privilege.to_sym)
225
+ if privilege.is_a?(Symbol)
226
+ super(privilege_from_symbol(privilege))
227
+ else
228
+ super
229
+ end
230
+ end
231
+
232
+ def intersects? (privileges)
233
+ intersection(privileges).length > 0
234
+ end
235
+
236
+ private
237
+ def privilege_from_symbol (privilege_sym)
238
+ Privilege.for_sym(privilege_sym, @engine)
239
+ end
240
+ end
241
+ end
242
+ end
243
+ end
@@ -0,0 +1,68 @@
1
+ # Authorization::AuthorizationHelper
2
+ require File.dirname(__FILE__) + '/authorization.rb'
3
+
4
+ module Authorization
5
+ module AuthorizationHelper
6
+
7
+ # If the current user meets the given privilege, permitted_to? returns true
8
+ # and yields to the optional block. The attribute checks that are defined
9
+ # in the authorization rules are only evaluated if an object is given
10
+ # for context.
11
+ #
12
+ # Examples:
13
+ # <% permitted_to? :create, :users do %>
14
+ # <%= link_to 'New', new_user_path %>
15
+ # <% end %>
16
+ # ...
17
+ # <% if permitted_to? :create, :users %>
18
+ # <%= link_to 'New', new_user_path %>
19
+ # <% else %>
20
+ # You are not allowed to create new users!
21
+ # <% end %>
22
+ # ...
23
+ # <% for user in @users %>
24
+ # <%= link_to 'Edit', edit_user_path(user) if permitted_to? :update, user %>
25
+ # <% end %>
26
+ #
27
+ # To pass in an object and override the context, you can use the optional
28
+ # options:
29
+ # permitted_to? :update, user, :context => :account
30
+ #
31
+ def permitted_to? (privilege, object_or_sym = nil, options = {}, &block)
32
+ controller.permitted_to?(privilege, object_or_sym, options, &block)
33
+ end
34
+
35
+ # While permitted_to? is used for authorization in views, in some cases
36
+ # content should only be shown to some users without being concerned
37
+ # with authorization. E.g. to only show the most relevant menu options
38
+ # to a certain group of users. That is what has_role? should be used for.
39
+ #
40
+ # Examples:
41
+ # <% has_role?(:sales) do %>
42
+ # <%= link_to 'All contacts', contacts_path %>
43
+ # <% end %>
44
+ # ...
45
+ # <% if has_role?(:sales) %>
46
+ # <%= link_to 'Customer contacts', contacts_path %>
47
+ # <% else %>
48
+ # ...
49
+ # <% end %>
50
+ #
51
+ def has_role? (*roles, &block)
52
+ controller.has_role?(*roles, &block)
53
+ end
54
+
55
+ # As has_role? except checks all roles included in the role hierarchy
56
+ def has_role_with_hierarchy?(*roles, &block)
57
+ controller.has_role_with_hierarchy?(*roles, &block)
58
+ end
59
+
60
+ def has_any_role?(*roles,&block)
61
+ controller.has_any_role?(*roles,&block)
62
+ end
63
+
64
+ def has_any_role_with_hierarchy?(*roles, &block)
65
+ controller.has_any_role_with_hierarchy?(*roles, &block)
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,645 @@
1
+ # Authorization::AuthorizationInController
2
+ require File.dirname(__FILE__) + '/authorization.rb'
3
+
4
+ module Authorization
5
+ module AuthorizationInController
6
+
7
+ def self.included(base) # :nodoc:
8
+ base.extend(ClassMethods)
9
+ base.hide_action :authorization_engine, :permitted_to?,
10
+ :permitted_to!
11
+ end
12
+
13
+ DEFAULT_DENY = false
14
+
15
+ # If attribute_check is set for filter_access_to, decl_auth will try to
16
+ # load the appropriate object from the current controller's model with
17
+ # the id from params[:id]. If that fails, a 404 Not Found is often the
18
+ # right way to handle the error. If you have additional measures in place
19
+ # that restricts the find scope, handling this error as a permission denied
20
+ # might be a better way. Set failed_auto_loading_is_not_found to false
21
+ # for the latter behaviour.
22
+ @@failed_auto_loading_is_not_found = true
23
+ def self.failed_auto_loading_is_not_found?
24
+ @@failed_auto_loading_is_not_found
25
+ end
26
+ def self.failed_auto_loading_is_not_found= (new_value)
27
+ @@failed_auto_loading_is_not_found = new_value
28
+ end
29
+
30
+ # Returns the Authorization::Engine for the current controller.
31
+ def authorization_engine
32
+ @authorization_engine ||= Authorization::Engine.instance
33
+ end
34
+
35
+ # If the current user meets the given privilege, permitted_to? returns true
36
+ # and yields to the optional block. The attribute checks that are defined
37
+ # in the authorization rules are only evaluated if an object is given
38
+ # for context.
39
+ #
40
+ # See examples for Authorization::AuthorizationHelper #permitted_to?
41
+ #
42
+ # If no object or context is specified, the controller_name is used as
43
+ # context.
44
+ #
45
+ def permitted_to? (privilege, object_or_sym = nil, options = {}, &block)
46
+ permitted_to!(privilege, object_or_sym, options.merge(:non_bang => true), &block)
47
+ end
48
+
49
+ # Works similar to the permitted_to? method, but
50
+ # throws the authorization exceptions, just like Engine#permit!
51
+ def permitted_to! (privilege, object_or_sym = nil, options = {}, &block)
52
+ context = object = nil
53
+ if object_or_sym.nil?
54
+ context = self.class.decl_auth_context
55
+ elsif !object_or_sym.respond_to?(:proxy_reflection) and object_or_sym.is_a?(Symbol)
56
+ context = object_or_sym
57
+ else
58
+ object = object_or_sym
59
+ end
60
+
61
+ non_bang = options.delete(:non_bang)
62
+ args = [
63
+ privilege,
64
+ {:user => current_user,
65
+ :object => object,
66
+ :context => context,
67
+ :skip_attribute_test => object.nil?}.merge(options)
68
+ ]
69
+ if non_bang
70
+ authorization_engine.permit?(*args, &block)
71
+ else
72
+ authorization_engine.permit!(*args, &block)
73
+ end
74
+ end
75
+
76
+ # While permitted_to? is used for authorization, in some cases
77
+ # content should only be shown to some users without being concerned
78
+ # with authorization. E.g. to only show the most relevant menu options
79
+ # to a certain group of users. That is what has_role? should be used for.
80
+ def has_role? (*roles, &block)
81
+ user_roles = authorization_engine.roles_for(current_user)
82
+ result = roles.all? do |role|
83
+ user_roles.include?(role)
84
+ end
85
+ yield if result and block_given?
86
+ result
87
+ end
88
+
89
+ # Intended to be used where you want to allow users with any single listed role to view
90
+ # the content in question
91
+ def has_any_role?(*roles,&block)
92
+ user_roles = authorization_engine.roles_for(current_user)
93
+ result = roles.any? do |role|
94
+ user_roles.include?(role)
95
+ end
96
+ yield if result and block_given?
97
+ result
98
+ end
99
+
100
+ # As has_role? except checks all roles included in the role hierarchy
101
+ def has_role_with_hierarchy?(*roles, &block)
102
+ user_roles = authorization_engine.roles_with_hierarchy_for(current_user)
103
+ result = roles.all? do |role|
104
+ user_roles.include?(role)
105
+ end
106
+ yield if result and block_given?
107
+ result
108
+ end
109
+
110
+ # As has_any_role? except checks all roles included in the role hierarchy
111
+ def has_any_role_with_hierarchy?(*roles, &block)
112
+ user_roles = authorization_engine.roles_with_hierarchy_for(current_user)
113
+ result = roles.any? do |role|
114
+ user_roles.include?(role)
115
+ end
116
+ yield if result and block_given?
117
+ result
118
+ end
119
+
120
+ protected
121
+ def filter_access_filter # :nodoc:
122
+ permissions = self.class.all_filter_access_permissions
123
+ all_permissions = permissions.select {|p| p.actions.include?(:all)}
124
+ matching_permissions = permissions.select {|p| p.matches?(action_name)}
125
+ allowed = false
126
+ auth_exception = nil
127
+ begin
128
+ allowed = if !matching_permissions.empty?
129
+ matching_permissions.all? {|perm| perm.permit!(self)}
130
+ elsif !all_permissions.empty?
131
+ all_permissions.all? {|perm| perm.permit!(self)}
132
+ else
133
+ !DEFAULT_DENY
134
+ end
135
+ rescue NotAuthorized => e
136
+ auth_exception = e
137
+ end
138
+
139
+ unless allowed
140
+ if all_permissions.empty? and matching_permissions.empty?
141
+ logger.warn "Permission denied: No matching filter access " +
142
+ "rule found for #{self.class.controller_name}.#{action_name}"
143
+ elsif auth_exception
144
+ logger.info "Permission denied: #{auth_exception}"
145
+ end
146
+ if respond_to?(:permission_denied)
147
+ # permission_denied needs to render or redirect
148
+ send(:permission_denied)
149
+ else
150
+ send(:render, :text => "You are not allowed to access this action.",
151
+ :status => :forbidden)
152
+ end
153
+ end
154
+ end
155
+
156
+ def load_controller_object (context_without_namespace = nil) # :nodoc:
157
+ instance_var = :"@#{context_without_namespace.to_s.singularize}"
158
+ model = context_without_namespace.to_s.classify.constantize
159
+ instance_variable_set(instance_var, model.find(params[:id]))
160
+ end
161
+
162
+ def load_parent_controller_object (parent_context_without_namespace) # :nodoc:
163
+ instance_var = :"@#{parent_context_without_namespace.to_s.singularize}"
164
+ model = parent_context_without_namespace.to_s.classify.constantize
165
+ instance_variable_set(instance_var, model.find(params[:"#{parent_context_without_namespace.to_s.singularize}_id"]))
166
+ end
167
+
168
+ def new_controller_object_from_params (context_without_namespace, parent_context_without_namespace) # :nodoc:
169
+ model_or_proxy = parent_context_without_namespace ?
170
+ instance_variable_get(:"@#{parent_context_without_namespace.to_s.singularize}").send(context_without_namespace.to_sym) :
171
+ context_without_namespace.to_s.classify.constantize
172
+ instance_var = :"@#{context_without_namespace.to_s.singularize}"
173
+ instance_variable_set(instance_var,
174
+ model_or_proxy.new(params[context_without_namespace.to_s.singularize]))
175
+ end
176
+
177
+ def new_controller_object_for_collection (context_without_namespace, parent_context_without_namespace) # :nodoc:
178
+ model_or_proxy = parent_context_without_namespace ?
179
+ instance_variable_get(:"@#{parent_context_without_namespace.to_s.singularize}").send(context_without_namespace.to_sym) :
180
+ context_without_namespace.to_s.classify.constantize
181
+ instance_var = :"@#{context_without_namespace.to_s.singularize}"
182
+ instance_variable_set(instance_var, model_or_proxy.new)
183
+ end
184
+
185
+ module ClassMethods
186
+ #
187
+ # Defines a filter to be applied according to the authorization of the
188
+ # current user. Requires at least one symbol corresponding to an
189
+ # action as parameter. The special symbol :+all+ refers to all action.
190
+ # The all :+all+ statement is only employed if no specific statement is
191
+ # present.
192
+ # class UserController < ApplicationController
193
+ # filter_access_to :index
194
+ # filter_access_to :new, :edit
195
+ # filter_access_to :all
196
+ # ...
197
+ # end
198
+ #
199
+ # The default is to allow access unconditionally if no rule matches.
200
+ # Thus, including the +filter_access_to+ :+all+ statement is a good
201
+ # idea, implementing a default-deny policy.
202
+ #
203
+ # When the access is denied, the method +permission_denied+ is called
204
+ # on the current controller, if defined. Else, a simple "you are not
205
+ # allowed" string is output. Log.info is given more information on the
206
+ # reasons of denial.
207
+ #
208
+ # def permission_denied
209
+ # flash[:error] = 'Sorry, you are not allowed to the requested page.'
210
+ # respond_to do |format|
211
+ # format.html { redirect_to(:back) rescue redirect_to('/') }
212
+ # format.xml { head :unauthorized }
213
+ # format.js { head :unauthorized }
214
+ # end
215
+ # end
216
+ #
217
+ # By default, required privileges are infered from the action name and
218
+ # the controller name. Thus, in UserController :+edit+ requires
219
+ # :+edit+ +users+. To specify required privilege, use the option :+require+
220
+ # filter_access_to :new, :create, :require => :create, :context => :users
221
+ #
222
+ # Without the :+attribute_check+ option, no constraints from the
223
+ # authorization rules are enforced because for some actions (collections,
224
+ # +new+, +create+), there is no object to evaluate conditions against. To
225
+ # allow attribute checks on all actions, it is a common pattern to provide
226
+ # custom objects through +before_filters+:
227
+ # class BranchesController < ApplicationController
228
+ # before_filter :load_company
229
+ # before_filter :new_branch_from_company_and_params,
230
+ # :only => [:index, :new, :create]
231
+ # filter_access_to :all, :attribute_check => true
232
+ #
233
+ # protected
234
+ # def new_branch_from_company_and_params
235
+ # @branch = @company.branches.new(params[:branch])
236
+ # end
237
+ # end
238
+ # NOTE: +before_filters+ need to be defined before the first
239
+ # +filter_access_to+ call.
240
+ #
241
+ # For further customization, a custom filter expression may be formulated
242
+ # in a block, which is then evaluated in the context of the controller
243
+ # on a matching request. That is, for checking two objects, use the
244
+ # following:
245
+ # filter_access_to :merge do
246
+ # permitted_to!(:update, User.find(params[:original_id])) and
247
+ # permitted_to!(:delete, User.find(params[:id]))
248
+ # end
249
+ # The block should raise a Authorization::AuthorizationError or return
250
+ # false if the access is to be denied.
251
+ #
252
+ # Later calls to filter_access_to with overlapping actions overwrite
253
+ # previous ones for that action.
254
+ #
255
+ # All options:
256
+ # [:+require+]
257
+ # Privilege required; defaults to action_name
258
+ # [:+context+]
259
+ # The privilege's context, defaults to decl_auth_context, which consists
260
+ # of controller_name, prepended by any namespaces
261
+ # [:+attribute_check+]
262
+ # Enables the check of attributes defined in the authorization rules.
263
+ # Defaults to false. If enabled, filter_access_to will use a context
264
+ # object from one of the following sources (in that order):
265
+ # * the method from the :+load_method+ option,
266
+ # * an instance variable named after the singular of the context
267
+ # (by default from the controller name, e.g. @post for PostsController),
268
+ # * a find on the context model, using +params+[:id] as id value.
269
+ # Any of these methods will only be employed if :+attribute_check+
270
+ # is enabled.
271
+ # [:+model+]
272
+ # The data model to load a context object from. Defaults to the
273
+ # context, singularized.
274
+ # [:+load_method+]
275
+ # Specify a method by symbol or a Proc object which should be used
276
+ # to load the object. Both should return the loaded object.
277
+ # If a Proc object is given, e.g. by way of
278
+ # +lambda+, it is called in the instance of the controller.
279
+ # Example demonstrating the default behaviour:
280
+ # filter_access_to :show, :attribute_check => true,
281
+ # :load_method => lambda { User.find(params[:id]) }
282
+ #
283
+
284
+ def filter_access_to (*args, &filter_block)
285
+ options = args.last.is_a?(Hash) ? args.pop : {}
286
+ options = {
287
+ :require => nil,
288
+ :context => nil,
289
+ :attribute_check => false,
290
+ :model => nil,
291
+ :load_method => nil
292
+ }.merge!(options)
293
+ privilege = options[:require]
294
+ context = options[:context]
295
+ actions = args.flatten
296
+
297
+ # prevent setting filter_access_filter multiple times
298
+ skip_before_filter :filter_access_filter
299
+ before_filter :filter_access_filter
300
+
301
+ filter_access_permissions.each do |perm|
302
+ perm.remove_actions(actions)
303
+ end
304
+ filter_access_permissions <<
305
+ ControllerPermission.new(actions, privilege, context,
306
+ options[:attribute_check],
307
+ options[:model],
308
+ options[:load_method],
309
+ filter_block)
310
+ end
311
+
312
+ # Collecting all the ControllerPermission objects from the controller
313
+ # hierarchy. Permissions for actions are overwritten by calls to
314
+ # filter_access_to in child controllers with the same action.
315
+ def all_filter_access_permissions # :nodoc:
316
+ ancestors.inject([]) do |perms, mod|
317
+ if mod.respond_to?(:filter_access_permissions)
318
+ perms +
319
+ mod.filter_access_permissions.collect do |p1|
320
+ p1.clone.remove_actions(perms.inject(Set.new) {|actions, p2| actions + p2.actions})
321
+ end
322
+ else
323
+ perms
324
+ end
325
+ end
326
+ end
327
+
328
+ # To DRY up the filter_access_to statements in restful controllers,
329
+ # filter_resource_access combines typical filter_access_to and
330
+ # before_filter calls, which set up the instance variables.
331
+ #
332
+ # The simplest case are top-level resource controllers with only the
333
+ # seven CRUD methods, e.g.
334
+ # class CompanyController < ApplicationController
335
+ # filter_resource_access
336
+ #
337
+ # def index...
338
+ # end
339
+ # Here, all CRUD actions are protected through a filter_access_to :all
340
+ # statement. :+attribute_check+ is enabled for all actions except for
341
+ # the collection action :+index+. To have an object for attribute checks
342
+ # available, filter_resource_access will set the instance variable
343
+ # @+company+ in before filters. For the member actions (:+show+, :+edit+,
344
+ # :+update+, :+destroy+) @company is set to Company.find(params[:id]).
345
+ # For +new+ actions (:+new+, :+create+), filter_resource_access creates
346
+ # a new object from company parameters: Company.new(params[:company].
347
+ #
348
+ # For nested resources, the parent object may be loaded automatically.
349
+ # class BranchController < ApplicationController
350
+ # filter_resource_access :nested_in => :companies
351
+ # end
352
+ # Again, the CRUD actions are protected. Now, for all CRUD actions,
353
+ # the parent object @company is loaded from params[:company_id]. It is
354
+ # also used when creating @branch for +new+ actions. Here, attribute_check
355
+ # is enabled for the collection :+index+ as well, checking attributes on a
356
+ # @company.branches.new method.
357
+ #
358
+ # In many cases, the default seven CRUD actions are not sufficient. As in
359
+ # the resource definition for routing you may thus give additional member,
360
+ # new and collection methods. The options allow you to specify the
361
+ # required privileges for each action by providing a hash or an array of
362
+ # pairs. By default, for each action the action name is taken as privilege
363
+ # (action search in the example below requires the privilege :index
364
+ # :companies). Any controller action that is not specified and does not
365
+ # belong to the seven CRUD actions is handled as a member method.
366
+ # class CompanyController < ApplicationController
367
+ # filter_resource_access :collection => [[:search, :index], :index],
368
+ # :additional_member => {:mark_as_key_company => :update}
369
+ # end
370
+ # The +additional_+* options add to the respective CRUD actions,
371
+ # the other options replace the respective CRUD actions.
372
+ #
373
+ # You can override the default object loading by implementing any of the
374
+ # following instance methods on the controller. Examples are given for the
375
+ # BranchController (with +nested_in+ set to :+companies+):
376
+ # [+new_branch_from_params+]
377
+ # Used for +new+ actions.
378
+ # [+new_branch_for_collection+]
379
+ # Used for +collection+ actions if the +nested_in+ option is set.
380
+ # [+load_branch+]
381
+ # Used for +member+ actions.
382
+ # [+load_company+]
383
+ # Used for all +new+, +member+, and +collection+ actions if the
384
+ # +nested_in+ option is set.
385
+ #
386
+ # All options:
387
+ # [:+member+]
388
+ # Member methods are actions like +show+, which have an params[:id] from
389
+ # which to load the controller object and assign it to @controller_name,
390
+ # e.g. @+branch+.
391
+ #
392
+ # By default, member actions are [:+show+, :+edit+, :+update+,
393
+ # :+destroy+]. Also, any action not belonging to the seven CRUD actions
394
+ # are handled as member actions.
395
+ #
396
+ # There are three different syntax to specify member, collection and
397
+ # new actions.
398
+ # * Hash: Lets you set the required privilege for each action:
399
+ # {:+show+ => :+show+, :+mark_as_important+ => :+update+}
400
+ # * Array of actions or pairs: [:+show+, [:+mark_as_important+, :+update+]],
401
+ # with single actions requiring the privilege of the same name as the method.
402
+ # * Single method symbol: :+show+
403
+ # [:+additional_member+]
404
+ # Allows to add additional member actions to the default resource +member+
405
+ # actions.
406
+ # [:+collection+]
407
+ # Collection actions are like :+index+, actions without any controller object
408
+ # to check attributes of. If +nested_in+ is given, a new object is
409
+ # created from the parent object, e.g. @company.branches.new. Without
410
+ # +nested_in+, attribute check is deactivated for these actions. By
411
+ # default, collection is set to :+index+.
412
+ # [:+additional_collection+]
413
+ # Allows to add additional collaction actions to the default resource +collection+
414
+ # actions.
415
+ # [:+new+]
416
+ # +new+ methods are actions such as +new+ and +create+, which don't
417
+ # receive a params[:id] to load an object from, but
418
+ # a params[:controller_name_singular] hash with attributes for a new
419
+ # object. The attributes will be used here to create a new object and
420
+ # check the object against the authorization rules. The object is
421
+ # assigned to @controller_name_singular, e.g. @branch.
422
+ #
423
+ # If +nested_in+ is given, the new object
424
+ # is created from the parent_object.controller_name
425
+ # proxy, e.g. company.branches.new(params[:branch]). By default,
426
+ # +new+ is set to [:new, :create].
427
+ # [:+additional_new+]
428
+ # Allows to add additional new actions to the default resource +new+ actions.
429
+ # [:+context+]
430
+ # The context is used to determine the model to load objects from for the
431
+ # before_filters and the context of privileges to use in authorization
432
+ # checks.
433
+ # [:+nested_in+]
434
+ # Specifies the parent controller if the resource is nested in another
435
+ # one. This is used to automatically load the parent object, e.g.
436
+ # @+company+ from params[:company_id] for a BranchController nested in
437
+ # a CompanyController.
438
+ # [:+shallow+]
439
+ # Only relevant when used in conjunction with +nested_in+. Specifies a nested resource
440
+ # as being a shallow nested resource, resulting in the controller not attempting to
441
+ # load a parent object for all member actions defined by +member+ and
442
+ # +additional_member+ or rather the default member actions (:+show+, :+edit+,
443
+ # :+update+, :+destroy+).
444
+ # [:+no_attribute_check+]
445
+ # Allows to set actions for which no attribute check should be perfomed.
446
+ # See filter_access_to on details. By default, with no +nested_in+,
447
+ # +no_attribute_check+ is set to all collections. If +nested_in+ is given
448
+ # +no_attribute_check+ is empty by default.
449
+ #
450
+ def filter_resource_access(options = {})
451
+ options = {
452
+ :new => [:new, :create],
453
+ :additional_new => nil,
454
+ :member => [:show, :edit, :update, :destroy],
455
+ :additional_member => nil,
456
+ :collection => [:index],
457
+ :additional_collection => nil,
458
+ #:new_method_for_collection => nil, # only symbol method name
459
+ #:new_method => nil, # only symbol method name
460
+ #:load_method => nil, # only symbol method name
461
+ :no_attribute_check => nil,
462
+ :context => nil,
463
+ :nested_in => nil,
464
+ }.merge(options)
465
+
466
+ new_actions = actions_from_option(options[:new]).merge(
467
+ actions_from_option(options[:additional_new]))
468
+ members = actions_from_option(options[:member]).merge(
469
+ actions_from_option(options[:additional_member]))
470
+ collections = actions_from_option(options[:collection]).merge(
471
+ actions_from_option(options[:additional_collection]))
472
+
473
+ options[:no_attribute_check] ||= collections.keys unless options[:nested_in]
474
+
475
+ unless options[:nested_in].blank?
476
+ load_parent_method = :"load_#{options[:nested_in].to_s.singularize}"
477
+ shallow_exceptions = options[:shallow] ? {:except => members.keys} : {}
478
+ before_filter shallow_exceptions do |controller|
479
+ if controller.respond_to?(load_parent_method)
480
+ controller.send(load_parent_method)
481
+ else
482
+ controller.send(:load_parent_controller_object, options[:nested_in])
483
+ end
484
+ end
485
+
486
+ new_for_collection_method = :"new_#{controller_name.singularize}_for_collection"
487
+ before_filter :only => collections.keys do |controller|
488
+ # new_for_collection
489
+ if controller.respond_to?(new_for_collection_method)
490
+ controller.send(new_for_collection_method)
491
+ else
492
+ controller.send(:new_controller_object_for_collection,
493
+ options[:context] || controller_name, options[:nested_in])
494
+ end
495
+ end
496
+ end
497
+
498
+ new_from_params_method = :"new_#{controller_name.singularize}_from_params"
499
+ before_filter :only => new_actions.keys do |controller|
500
+ # new_from_params
501
+ if controller.respond_to?(new_from_params_method)
502
+ controller.send(new_from_params_method)
503
+ else
504
+ controller.send(:new_controller_object_from_params,
505
+ options[:context] || controller_name, options[:nested_in])
506
+ end
507
+ end
508
+ load_method = :"load_#{controller_name.singularize}"
509
+ before_filter :only => members.keys do |controller|
510
+ # load controller object
511
+ if controller.respond_to?(load_method)
512
+ controller.send(load_method)
513
+ else
514
+ controller.send(:load_controller_object, options[:context] || controller_name)
515
+ end
516
+ end
517
+ filter_access_to :all, :attribute_check => true, :context => options[:context]
518
+
519
+ members.merge(new_actions).merge(collections).each do |action, privilege|
520
+ if action != privilege or (options[:no_attribute_check] and options[:no_attribute_check].include?(action))
521
+ filter_options = {
522
+ :context => options[:context],
523
+ :attribute_check => !options[:no_attribute_check] || !options[:no_attribute_check].include?(action)
524
+ }
525
+ filter_options[:require] = privilege if action != privilege
526
+ filter_access_to(action, filter_options)
527
+ end
528
+ end
529
+ end
530
+
531
+ # Returns the context for authorization checks in the current controller.
532
+ # Uses the controller_name and prepends any namespaces underscored and
533
+ # joined with underscores.
534
+ #
535
+ # E.g.
536
+ # AllThosePeopleController => :all_those_people
537
+ # AnyName::Space::ThingsController => :any_name_space_things
538
+ #
539
+ def decl_auth_context
540
+ prefixes = name.split('::')[0..-2].map(&:underscore)
541
+ ((prefixes + [controller_name]) * '_').to_sym
542
+ end
543
+
544
+ protected
545
+ def filter_access_permissions # :nodoc:
546
+ unless filter_access_permissions?
547
+ ancestors[1..-1].reverse.each do |mod|
548
+ mod.filter_access_permissions if mod.respond_to?(:filter_access_permissions)
549
+ end
550
+ end
551
+ class_variable_set(:@@declarative_authorization_permissions, {}) unless filter_access_permissions?
552
+ class_variable_get(:@@declarative_authorization_permissions)[self.name] ||= []
553
+ end
554
+
555
+ def filter_access_permissions? # :nodoc:
556
+ class_variable_defined?(:@@declarative_authorization_permissions)
557
+ end
558
+
559
+ def actions_from_option (option) # :nodoc:
560
+ case option
561
+ when nil
562
+ {}
563
+ when Symbol, String
564
+ {option.to_sym => option.to_sym}
565
+ when Hash
566
+ option
567
+ when Enumerable
568
+ option.each_with_object({}) do |action, hash|
569
+ if action.is_a?(Array)
570
+ raise "Unexpected option format: #{option.inspect}" if action.length != 2
571
+ hash[action.first] = action.last
572
+ else
573
+ hash[action.to_sym] = action.to_sym
574
+ end
575
+ end
576
+ end
577
+ end
578
+ end
579
+ end
580
+
581
+ class ControllerPermission # :nodoc:
582
+ attr_reader :actions, :privilege, :context, :attribute_check
583
+ def initialize (actions, privilege, context, attribute_check = false,
584
+ load_object_model = nil, load_object_method = nil,
585
+ filter_block = nil)
586
+ @actions = actions.to_set
587
+ @privilege = privilege
588
+ @context = context
589
+ @load_object_model = load_object_model
590
+ @load_object_method = load_object_method
591
+ @filter_block = filter_block
592
+ @attribute_check = attribute_check
593
+ end
594
+
595
+ def matches? (action_name)
596
+ @actions.include?(action_name.to_sym)
597
+ end
598
+
599
+ def permit! (contr)
600
+ if @filter_block
601
+ return contr.instance_eval(&@filter_block)
602
+ end
603
+ object = @attribute_check ? load_object(contr) : nil
604
+ privilege = @privilege || :"#{contr.action_name}"
605
+
606
+ contr.authorization_engine.permit!(privilege,
607
+ :user => contr.send(:current_user),
608
+ :object => object,
609
+ :skip_attribute_test => !@attribute_check,
610
+ :context => @context || contr.class.decl_auth_context)
611
+ end
612
+
613
+ def remove_actions (actions)
614
+ @actions -= actions
615
+ self
616
+ end
617
+
618
+ private
619
+ def load_object(contr)
620
+ if @load_object_method and @load_object_method.is_a?(Symbol)
621
+ contr.send(@load_object_method)
622
+ elsif @load_object_method and @load_object_method.is_a?(Proc)
623
+ contr.instance_eval(&@load_object_method)
624
+ else
625
+ load_object_model = @load_object_model ||
626
+ (@context ? @context.to_s.classify.constantize : contr.class.controller_name.classify.constantize)
627
+ instance_var = :"@#{load_object_model.name.underscore}"
628
+ object = contr.instance_variable_get(instance_var)
629
+ unless object
630
+ begin
631
+ object = load_object_model.find(contr.params[:id])
632
+ rescue => e
633
+ contr.logger.debug("filter_access_to tried to find " +
634
+ "#{load_object_model} from params[:id] " +
635
+ "(#{contr.params[:id].inspect}), because attribute_check is enabled " +
636
+ "and #{instance_var.to_s} isn't set, but failed: #{e.class.name}: #{e}")
637
+ raise if AuthorizationInController.failed_auto_loading_is_not_found?
638
+ end
639
+ contr.instance_variable_set(instance_var, object)
640
+ end
641
+ object
642
+ end
643
+ end
644
+ end
645
+ end