Module: Mpp::Server::Decorator

Extended by:
T::Sig
Defined in:
lib/mpp/server/decorator.rb

Class Method Summary collapse

Class Method Details

.make_challenge_response(challenge, realm, extra_headers: {}) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/mpp/server/decorator.rb', line 22

def make_challenge_response(challenge, realm, extra_headers: {})
  challenges = challenge.is_a?(Array) ? challenge : [challenge]
  Kernel.raise ArgumentError, "at least one challenge is required" if challenges.empty?

  first = challenges.first
  error = Mpp::PaymentRequiredError.new(realm: realm, description: first.description)
  body = JSON.generate(error.to_problem_details(challenge_id: first.id))
  www = challenges.map { |item| item.to_www_authenticate(realm) }

  headers = {
    "WWW-Authenticate" => ((www.length == 1) ? www.first : www),
    "Cache-Control" => "no-store",
    "Content-Type" => "application/problem+json"
  }
  extra_headers.each do |key, value|
    next if value.nil?

    headers[key] = value
  end
  Mpp::Server::Middleware.mark_authorization_bound_response(
    headers,
    vary: extra_headers.key?("PAYMENT-REQUIRED") ? ["Authorization", "PAYMENT-SIGNATURE"] : ["Authorization"]
  )
  {
    "_mpp_challenge" => true,
    "status" => 402,
    "headers" => headers,
    "body" => body
  }
end