Module: Pragma::Operation::Authorization::InstanceMethods

Defined in:
lib/pragma/operation/authorization.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#after_authorization(result) ⇒ Object

Runs after authorization is done.



100
101
# File 'lib/pragma/operation/authorization.rb', line 100

def after_authorization(result)
end

#authorize(authorizable) ⇒ Boolean

Authorizes this operation on the provided resource or policy.

If no policy was defined, simply returns true.



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/pragma/operation/authorization.rb', line 60

def authorize(authorizable)
  return true unless compute_policy_klass

  # rubocop:disable Metrics/LineLength
  policy = if Object.const_defined?('Pragma::Policy::Base') && authorizable.is_a?(Pragma::Policy::Base)
    authorizable
  else
    build_policy(authorizable)
  end
  # rubocop:enable Metrics/LineLength

  if Object.const_defined?('Pragma::Contract::Base') && authorizable.is_a?(Pragma::Contract::Base)
    authorizable.deserialize(params)
  end

  policy.send("#{self.class.operation_name}?").tap do |result|
    after_authorization result
  end
end

#authorize!(authorizable) ⇒ Object

Authorizes this operation on the provided resource or policy. If the user is not authorized to perform the operation, responds with 403 Forbidden and an error body and halts the execution.



85
86
87
88
89
90
91
92
93
94
95
# File 'lib/pragma/operation/authorization.rb', line 85

def authorize!(authorizable)
  return if authorize(authorizable)

  respond_with!(
    status: :forbidden,
    resource: {
      error_type: :forbidden,
      error_message: 'You are not authorized to perform this operation.'
    }
  )
end

#authorize_collection(collection) ⇒ Pragma::Decorator::Base|Enumerable

Scopes the provided collection.

If no policy class is defined, simply returns the collection.



110
111
112
113
114
115
116
117
118
# File 'lib/pragma/operation/authorization.rb', line 110

def authorize_collection(collection)
  policy_klass = compute_policy_klass
  return collection unless policy_klass

  policy_klass.accessible_by(
    user: current_user,
    scope: collection
  )
end

#build_policy(resource) ⇒ Pragma::Policy::Base

Builds the policy for the current user and the given resource, using the previously defined policy class.

See Also:



46
47
48
49
50
51
# File 'lib/pragma/operation/authorization.rb', line 46

def build_policy(resource)
  policy_klass = compute_policy_klass
  return resource unless policy_klass

  policy_klass.new(user: current_user, resource: resource)
end

#compute_policy_klassObject



120
121
122
123
124
125
126
# File 'lib/pragma/operation/authorization.rb', line 120

def compute_policy_klass
  if self.class.policy_klass.is_a?(Proc)
    self.class.policy_klass.call(context)
  else
    self.class.policy_klass
  end
end