Class: Mpp::Server::Middleware

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/mpp/server/middleware.rb

Overview

Rack middleware that intercepts requests requiring payment.

The downstream app signals payment is needed by setting env to a hash with at least :amount, and optionally :currency, :recipient, :description, :expires, etc.

Example:

use Mpp::Server::Middleware, handler: my_handler

# In your app:
env["mpp.charge"] = { amount: "1.00" }

Defined Under Namespace

Classes: RackInputCapture

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, handler:) ⇒ Middleware

Returns a new instance of Middleware.



23
24
25
26
# File 'lib/mpp/server/middleware.rb', line 23

def initialize(app, handler:)
  @app = T.let(app, T.untyped)
  @handler = T.let(handler, Mpp::Server::MppHandler)
end

Class Method Details

.mark_authorization_bound_response(headers) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/mpp/server/middleware.rb', line 59

def self.mark_authorization_bound_response(headers)
  headers["Cache-Control"] = "no-store"

  vary_values = headers["Vary"].to_s.split(",").map do |value|
    value.strip.downcase
  end
  return if vary_values.include?("*") || vary_values.include?("authorization")

  headers["Vary"] = [headers["Vary"], "Authorization"]
    .compact
    .reject(&:empty?)
    .join(", ")
end

Instance Method Details

#call(env) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/mpp/server/middleware.rb', line 29

def call(env)
  authorization = env["HTTP_AUTHORIZATION"]
  body_capture = capture_request_body(env)
  status, headers, body = @app.call(env)

  charge_opts = env["mpp.charge"]
  return [status, headers, body] unless charge_opts

  request_body = body_capture&.materialize
  env["rack.input"] = StringIO.new(request_body || "") if body_capture

  amount = charge_opts[:amount]
  opts = charge_opts.except(:amount, :body)
  opts[:mppx_scope] ||= mppx_scope(env)

  result = @handler.charge(authorization, amount, **opts, body: request_body)

  if result.is_a?(Mpp::Challenge)
    resp = Mpp::Server::Decorator.make_challenge_response(result, @handler.realm)
    return [resp["status"], resp["headers"], [resp["body"]]]
  end

  _credential, receipt = result
  headers["Payment-Receipt"] = receipt.to_payment_receipt
  self.class.mark_authorization_bound_response(headers)

  [status, headers, body]
end