Skip to content

Commit

Permalink
use signature_method dynamically in api call
Browse files Browse the repository at this point in the history
  • Loading branch information
pgvandelden committed Mar 25, 2021
1 parent 3b69ae1 commit 078507c
Show file tree
Hide file tree
Showing 2 changed files with 249 additions and 195 deletions.
38 changes: 24 additions & 14 deletions lib/lti_result.ex
Original file line number Diff line number Diff line change
Expand Up @@ -27,31 +27,41 @@ defmodule LTIResult do
{:ok, "iyyQNRQyXTlpLJPJns3ireWjQxo%3D"}
"""
def signature(url, oauth_header, secret) do
{parameters, [{"oauth_signature", received_signature}]} =
extract_header_elements(oauth_header)

with {:ok, _} <- validate_parameters(parameters) do
basestring = base_string(url, parameters)

signature = generate_signature(secret, basestring)

if signature == received_signature do
{:ok, signature}
else
{:error, [:unmatching_signatures]}
with {parameters, [{"oauth_signature", received_signature}]} <-
extract_header_elements(oauth_header),
{:ok, _} <- validate_parameters(parameters),
{_, signature_method} <-
List.keyfind(
parameters,
"oauth_signature_method",
0,
{"oauth_signature_method", "HMAC-SHA1"}
),
basestring <- base_string(url, parameters),
signature <- generate_signature(secret, signature_method, basestring) do
case signature == received_signature do
true ->
{:ok, signature}

false ->
{:error, [:unmatching_signatures]}
end
end
end

defp generate_signature(secret, basestring) do
:sha
defp generate_signature(secret, signature_method, basestring) do
signature_method
|> get_signature_method()
|> :crypto.hmac(
percent_encode(secret) <> "&",
basestring
)
|> Base.encode64()
end

defp get_signature_method("HMAC-SHA256"), do: :sha256
defp get_signature_method(_), do: :sha

defp extract_header_elements(header) do
header
|> String.trim_leading("OAuth ")
Expand Down
Loading

0 comments on commit 078507c

Please sign in to comment.