PlugSetRequestRawData v0.1.1 PlugSetRequestRawData
This plug will set raw request data in conn.private[:raw_request_data]
, where conn is of type %Plug.Conn{}
Oftenly, we will need exact copies of raw request data in our Phoenix controller or our plug based apps. For example, when we are receiving web hook requests from third party apps. These third party requests generally have their own ways of verifying the contents are actually being sent from them. Many of the most common ways involve taking the raw request data and append with some salts or other values (that are given to you from the thirdparty apps) and then encrypt/hash them to get some unique values. And Finally, we use this unique values to match with some secret values to verify that these requests are actually were been sent from the third party apps that we know.
Generally this raw request data is discarded once %Plug.Conn{}
connection is passed through Plug.Parsers
.
To see more about this why it is discarded checkout documentation here.
This Plug is inspired by following discussions and PR on Availability of raw body bytes when using parsers
and Add a custom body reader option to Parsers,
and also on instructions to extract raw_request_data
from Custom body reader.
Installation Instruction
Add :plug_set_request_raw_data
to deps()
in mix.exs
file
defp deps do
[
...,
{:plug_set_request_raw_data, "~> 0.1.1"}
]
end
Usage Instruction
In your Endpoint
module add plug PlugSetRequestRawData
and a map that has a key :check
,
with value of annoynymous function in the form &Module.function/arbitry
.
This annonymous function should take one parameter that is %Plug.Conn
,
which evalates to either true
or false
. If the annonymous function evaluates to true
the plug will put raw data in conn.private[:raw_request_data]
,
if it evalutates to false
, the plug will not do anything.
defmodule MyAppWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :my_app
...
plug(PlugSetRequestRawData, %{check: &MyAppWeb.Check.check/1}) # Make sure that it is before Plug.Parsers plug
plug(
Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Poison
)
...
end
defmodule MyAppWeb.Check do
alias Plug.Conn
def check(%Conn{}), do: true
end
Contributions
Merge Requests are welcome!. The code repository is hosted at https://gitlab.com/blisscs/plug_set_request_raw_data.
And for any current issues checkout https://gitlab.com/blisscs/plug_set_request_raw_data/issues.
License
PlugSetRequestRawData
is licensed under MIT License.