lib/pragma/operation/authorization.rb in pragma-operation-0.1.2 vs lib/pragma/operation/authorization.rb in pragma-operation-1.0.0

- old
+ new

@@ -16,21 +16,28 @@ # @param klass [Class] a subclass of +Pragma::Policy::Base+ def policy(klass) @policy = klass end + # Returns the policy class. + # + # @return [Class] + def policy_klass + @policy + end + # Builds the policy for the given user and resource, using the previous defined policy # class. # # @param user [Object] # @param resource [Object] # # @return [Pragma::Policy::Base] # # @see #policy def build_policy(user:, resource:) - @policy.new(user: user, resource: resource) + policy_klass.new(user: user, resource: resource) end end module InstanceMethods # :nodoc: # Builds the policy for the current user and the given resource, using the previously @@ -46,15 +53,19 @@ self.class.build_policy(user: current_user, resource: resource) end # Authorizes this operation on the provided resource or policy. # + # If no policy was defined, simply returns true. + # # @param authorizable [Pragma::Policy::Base|Object] resource or policy # # @return [Boolean] whether the operation is authorized def authorize(authorizable) - policy = if defined?(Pragma::Policy::Base) && authorizable.is_a?(Pragma::Policy::Base) + return true unless self.class.policy_klass + + policy = if authorizable.is_a?(self.class.policy_klass) authorizable else build_policy(authorizable) end @@ -73,9 +84,25 @@ status: :forbidden, resource: { error_type: :forbidden, error_message: 'You are not authorized to perform this operation.' } + ) + end + + # Scopes the provided collection. + # + # If no policy class is defined, simply returns the collection. + # + # @param collection [Enumerable] + # + # @return [Pragma::Decorator::Base|Enumerable] + def authorize_collection(collection) + return collection unless self.class.policy_klass + + self.class.policy_klass.accessible_by( + user: current_user, + scope: collection ) end end end end