Class: DeepUnrest::Authorization::PunditStrategy

Inherits:
BaseStrategy
  • Object
show all
Defined in:
lib/deep_unrest/authorization/pundit_strategy.rb

Class Method Summary collapse

Class Method Details

.auth_error_message(user, scope) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/deep_unrest/authorization/pundit_strategy.rb', line 19

def self.auth_error_message(user, scope)
  if user
    actor = "#{user.class.name} with id '#{user.id}' is"
  else
    actor = "Anonymous users are"
  end

  target = (scope[:type] || scope[:key]).to_s.classify
  unless %i[create update_all].include? scope[:scope_type]
    target_id = (scope[:id] || scope.dig(:query, :id)).to_s.gsub('.', '')
    target += " with id '#{target_id.to_s.gsub('.', '')}'"
  end

  msg = "#{actor} not authorized to #{scope[:scope_type].to_s.downcase} #{target}"

  [{ title: msg,
     source: { pointer: scope[:path] } }].to_json
end

.authorize(scopes, user) ⇒ Object



56
57
58
59
60
61
62
63
# File 'lib/deep_unrest/authorization/pundit_strategy.rb', line 56

def self.authorize(scopes, user)
  scopes.each do |s|
    allowed = get_entity_authorization(s, user)
    unless allowed
      raise DeepUnrest::Unauthorized, auth_error_message(user, s)
    end
  end
end

.get_authorized_scope(user, klass) ⇒ Object



14
15
16
17
# File 'lib/deep_unrest/authorization/pundit_strategy.rb', line 14

def self.get_authorized_scope(user, klass)
  policy = get_policy(klass)
  policy::Scope.new(user, klass).resolve
end

.get_entity_authorization(scope, user) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/deep_unrest/authorization/pundit_strategy.rb', line 38

def self.get_entity_authorization(scope, user)
  if %i[create update_all index destroy_all].include?(scope[:scope_type])
    target = scope[:klass]
  elsif scope[:scope]
    # TODO: deprecate this part of the clause following write endpoint refactor
    target = scope[:scope][:base].send(scope[:scope][:method],
                                       *scope[:scope][:arguments])
  else
    return true unless scope[:query][:id]

    target = scope[:klass].find(scope[:query][:id])
  end

  Pundit.policy!(user, target).send(get_policy_name(scope[:scope_type]))
rescue Pundit::NotDefinedError
  false
end

.get_policy(klass) ⇒ Object



10
11
12
# File 'lib/deep_unrest/authorization/pundit_strategy.rb', line 10

def self.get_policy(klass)
  "#{klass}Policy".constantize
end

.get_policy_name(method) ⇒ Object



6
7
8
# File 'lib/deep_unrest/authorization/pundit_strategy.rb', line 6

def self.get_policy_name(method)
  "#{method}?".to_sym
end