Last active
November 8, 2021 15:40
-
-
Save ryanwinchester/ab49855e9acb7352507b8fa92ffe69d0 to your computer and use it in GitHub Desktop.
Twilio signature module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule TwilioSignature do | |
@moduledoc """ | |
Twilio signatures module. | |
""" | |
@doc """ | |
Generate the Twilio signature from a request. | |
See: https://www.twilio.com/docs/usage/security#validating-requests | |
## Example | |
iex> url = "https://mycompany.com/myapp.php?foo=1&bar=2" | |
iex> params = %{ | |
...> "CallSid" => "CA1234567890ABCDE", | |
...> "From" => "+12349013030", | |
...> "To" => "+18005551212", | |
...> "Caller" => "+12349013030", | |
...> "Digits" => "1234" | |
...> } | |
iex> TwilioSignature.generate(url, params, "12345") | |
"0/KCTR6DLpKmkAf8muzZqo1nDgQ=" | |
""" | |
@spec generate(String.t(), map(), String.t()) :: String.t() | |
def generate(url, params, secret) do | |
sorted_params_iolist = | |
params | |
|> Enum.sort_by(fn {k, v} -> [k, v] end) | |
|> List.flatten() | |
[url | sorted_params_iolist] | |
|> then(&:crypto.mac(:hmac, :sha, secret, &1)) | |
|> Base.encode64() | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment