Current section
Files
Jump to
Current section
Files
lib/teac/plug/cache_body_reader.ex
defmodule Teac.Plug.CacheBodyReader do
@moduledoc """
A `Plug.Parsers` body reader that caches the raw request body in `conn.assigns`.
Use this with `Plug.Parsers` in your Phoenix `Endpoint` so that
`Teac.Plug.EventSub` can verify the Twitch HMAC signature after the body
has already been parsed.
## Endpoint configuration
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
body_reader: {Teac.Plug.CacheBodyReader, :read_body, []},
json_decoder: JSON
The raw body is stored under `conn.assigns[:raw_body]` as a binary string.
"""
def read_body(conn, opts) do
case Plug.Conn.read_body(conn, opts) do
{:ok, body, conn} ->
conn = Plug.Conn.assign(conn, :raw_body, body)
{:ok, body, conn}
{:more, partial, conn} ->
# For large bodies, accumulate chunks. Webhook payloads are small so
# this path is rarely hit, but we handle it for correctness.
conn = Plug.Conn.assign(conn, :raw_body, partial)
{:more, partial, conn}
other ->
other
end
end
end