viva-declarative_authorization 0.3.2.2.1

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