-
Notifications
You must be signed in to change notification settings - Fork 14
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Use a pluggable authorizer to calculated the Authorization
header field value.
#65
Open
pezra
wants to merge
6
commits into
master
Choose a base branch
from
authorizer
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
72341ea
authorizer protocol and basic implementations
pezra 1f1a3bf
use authorizer to calculate `Authorization` header field value.
pezra 85a53dc
update docs and bump version
pezra 9c260d1
uglify the code
pezra 4fa54c1
improve Authorizer type docs
pezra 264a660
better authorization interface
pezra File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
defprotocol ExHal.Authorizer do | ||
@typedoc """ | ||
The value of the `Authorization` header field. | ||
""" | ||
@type credentials :: String.t() | ||
|
||
@typedoc """ | ||
A URL. | ||
""" | ||
@type url :: String.t() | ||
|
||
@typedoc """ | ||
An object that implements the ExHal.Authorizer protocol. | ||
""" | ||
@type authorizer :: any() | ||
|
||
@typedoc """ | ||
Name of a HTTP header field. | ||
""" | ||
@type header_field_name :: String.t | ||
|
||
@doc """ | ||
|
||
Called before each request to calculate any header fields needed to | ||
authorize the request. A common return would be | ||
|
||
%{"Authorization" => "Bearer <sometoken>"} | ||
|
||
If the URL is unrecognized or no header fields are appropriate or | ||
needed this function should return and empty map. | ||
|
||
""" | ||
@spec authorization(authorizer, url()) :: %{optional(header_field_name()) => String.t()} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm confused how a Map key can be |
||
def authorization(authorizer, url) | ||
end |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,57 +5,91 @@ defmodule ExHal.Client do | |
## Examples | ||
|
||
iex> ExHal.Client.new() | ||
%ExHal.Client{} | ||
...> |> ExHal.Client.get("http://haltalk.herokuapp.com/") | ||
%ExHal.Document{...} | ||
|
||
iex> ExHal.Client.new() | ||
...> |> ExHal.Client.post("http://haltalk.herokuapp.com/signup", ~s( | ||
...> { "username": "fred", | ||
...> "password": "pwnme", | ||
...> "real_name": "Fred Wilson" } | ||
...> )) | ||
%ExHal.Document{...} | ||
|
||
iex> authorizer = ExHal.SimpleAuthorizer.new("http://haltalk.herokuapp.com", | ||
...> "Bearer my-token") | ||
iex> ExHal.Client.new() | ||
...> |> ExHal.Client.add_headers("Prefer": "minimal") | ||
...> |> ExHal.Client.set_authorizer(authorizer) | ||
%ExHal.Client{...} | ||
""" | ||
|
||
require Logger | ||
alias ExHal.{Document, NonHalResponse, ResponseHeader} | ||
alias ExHal.{Document, NonHalResponse, ResponseHeader, Authorizer, NullAuthorizer} | ||
|
||
@logger Application.get_env(:exhal, :logger, Logger) | ||
@http_client Application.get_env(:exhal, :http_client, HTTPoison) | ||
pezra marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
@typedoc """ | ||
Represents a client configuration/connection. Create with `new` function. | ||
""" | ||
@opaque t :: %__MODULE__{} | ||
defstruct headers: [], opts: [follow_redirect: true] | ||
defstruct authorizer: NullAuthorizer.new(), | ||
headers: %{}, | ||
opts: [follow_redirect: true] | ||
|
||
@typedoc """ | ||
The return value of any function that makes an HTTP request. | ||
""" | ||
@type http_response :: | ||
{:ok, Document.t() | NonHalResponse.t(), ResponseHeader.t()} | ||
| {:error, Document.t() | NonHalResponse.t(), ResponseHeader.t() } | ||
| {:error, Error.t()} | ||
{:ok, Document.t() | NonHalResponse.t(), ResponseHeader.t()} | ||
| {:error, Document.t() | NonHalResponse.t(), ResponseHeader.t()} | ||
| {:error, Error.t()} | ||
|
||
@doc """ | ||
Returns a new client. | ||
""" | ||
@spec new(Keyword.t(), Keyword.t()) :: __MODULE__.t() | ||
def new(headers, follow_redirect: follow) do | ||
%__MODULE__{headers: headers, opts: [follow_redirect: follow]} | ||
end | ||
@spec new() :: t | ||
def new(), do: %__MODULE__{} | ||
|
||
@spec new(Keyword.t()) :: t | ||
def new(headers: headers), | ||
do: %__MODULE__{headers: normalize_headers(headers), opts: [follow_redirect: true]} | ||
|
||
def new(follow_redirect: follow), do: %__MODULE__{opts: [follow_redirect: follow]} | ||
|
||
def new(headers: headers, follow_redirect: follow), | ||
do: %__MODULE__{headers: normalize_headers(headers), opts: [follow_redirect: follow]} | ||
|
||
@spec new(Keyword.t()) :: __MODULE__.t() | ||
def new(headers) do | ||
new(headers, follow_redirect: true) | ||
# deprecated call patterns | ||
def new(headers) when is_list(headers) do | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. do these need the |
||
%__MODULE__{headers: normalize_headers(headers), opts: [follow_redirect: true]} | ||
end | ||
|
||
@spec new() :: __MODULE__.t() | ||
def new() do | ||
new([], follow_redirect: true) | ||
@spec new(Keyword.t(), Keyword.t()) :: t | ||
def new(headers, follow_redirect: follow) do | ||
new(headers: headers, follow_redirect: follow) | ||
end | ||
|
||
@doc """ | ||
Returns client that will include the specified headers in any request | ||
made with it. | ||
""" | ||
@spec add_headers(__MODULE__.t(), Keyword.t()) :: __MODULE__.t() | ||
@spec add_headers(t, Keyword.t()) :: t | ||
def add_headers(client, headers) do | ||
updated_headers = merge_headers(client.headers, headers) | ||
updated_headers = merge_headers(client.headers, normalize_headers(headers)) | ||
|
||
%__MODULE__{client | headers: updated_headers} | ||
end | ||
|
||
@doc """ | ||
Returns a client that will authorize requests using the specified authorizer. | ||
""" | ||
@spec set_authorizer(t, Authorizer.t()) :: t | ||
def set_authorizer(client, new_authorizer) do | ||
%__MODULE__{client | authorizer: new_authorizer} | ||
end | ||
|
||
defmacrop log_req(method, url, do: block) do | ||
quote do | ||
{time, result} = :timer.tc(fn -> unquote(block) end) | ||
|
@@ -64,60 +98,63 @@ defmodule ExHal.Client do | |
end | ||
end | ||
|
||
@callback get(__MODULE__.t, String.t, Keyword.t) :: http_response() | ||
@callback get(__MODULE__.t(), String.t(), Keyword.t()) :: http_response() | ||
def get(client, url, opts \\ []) do | ||
{headers, poison_opts} = figure_headers_and_opt(opts, client) | ||
{headers, poison_opts} = figure_headers_and_opt(opts, client, url) | ||
|
||
log_req("GET", url) do | ||
HTTPoison.get(url, headers, poison_opts) | ||
@http_client.get(url, headers, poison_opts) | ||
|> extract_return(client) | ||
end | ||
end | ||
|
||
@callback post(__MODULE__.t, String.t, <<>>, Keyword.t) :: http_response() | ||
@callback post(__MODULE__.t(), String.t(), <<>>, Keyword.t()) :: http_response() | ||
def post(client, url, body, opts \\ []) do | ||
{headers, poison_opts} = figure_headers_and_opt(opts, client) | ||
{headers, poison_opts} = figure_headers_and_opt(opts, client, url) | ||
|
||
log_req("POST", url) do | ||
HTTPoison.post(url, body, headers, poison_opts) | ||
@http_client.post(url, body, headers, poison_opts) | ||
|> extract_return(client) | ||
end | ||
end | ||
|
||
@callback put(__MODULE__.t, String.t, <<>>, Keyword.t) :: http_response() | ||
@callback put(__MODULE__.t(), String.t(), <<>>, Keyword.t()) :: http_response() | ||
def put(client, url, body, opts \\ []) do | ||
{headers, poison_opts} = figure_headers_and_opt(opts, client) | ||
{headers, poison_opts} = figure_headers_and_opt(opts, client, url) | ||
|
||
log_req("PUT", url) do | ||
HTTPoison.put(url, body, headers, poison_opts) | ||
@http_client.put(url, body, headers, poison_opts) | ||
|> extract_return(client) | ||
end | ||
end | ||
|
||
@callback patch(__MODULE__.t, String.t, <<>>, Keyword.t) :: http_response() | ||
@callback patch(__MODULE__.t(), String.t(), <<>>, Keyword.t()) :: http_response() | ||
def patch(client, url, body, opts \\ []) do | ||
{headers, poison_opts} = figure_headers_and_opt(opts, client) | ||
{headers, poison_opts} = figure_headers_and_opt(opts, client, url) | ||
|
||
log_req("PATCH", url) do | ||
HTTPoison.patch(url, body, headers, poison_opts) | ||
@http_client.patch(url, body, headers, poison_opts) | ||
|> extract_return(client) | ||
end | ||
end | ||
|
||
# Private functions | ||
|
||
defp figure_headers_and_opt(opts, client) do | ||
{local_headers, local_opts} = Keyword.pop(Keyword.new(opts), :headers, []) | ||
defp figure_headers_and_opt(opts, client, url) do | ||
{local_headers, local_opts} = Keyword.pop(Keyword.new(opts), :headers, %{}) | ||
|
||
headers = | ||
client.headers | ||
|> merge_headers(normalize_headers(local_headers)) | ||
|> merge_headers(Authorizer.authorization(client.authorizer, url)) | ||
|
||
headers = merge_headers(client.headers, local_headers) | ||
poison_opts = merge_poison_opts(client.opts, local_opts) | ||
|
||
{headers, poison_opts} | ||
end | ||
|
||
defp merge_headers(old_headers, new_headers) do | ||
old_headers | ||
|> Keyword.merge(new_headers, fn _k, v1, v2 -> List.wrap(v1) ++ List.wrap(v2) end) | ||
Map.merge(old_headers, new_headers, fn _k, v1, v2 -> List.wrap(v1) ++ List.wrap(v2) end) | ||
end | ||
|
||
@default_poison_opts [follow_redirect: true] | ||
|
@@ -150,4 +187,8 @@ defmodule ExHal.Client do | |
{:error, _} -> NonHalResponse.from_httpoison_response(resp) | ||
end | ||
end | ||
|
||
defp normalize_headers(headers) do | ||
Enum.into(headers, %{}, fn {k, v} -> {to_string(k), v} end) | ||
end | ||
end |
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
defmodule ExHal.HttpClient do | ||
@callback get(String.t(), HTTPoison.Base.headers(), Keyword.t()) :: | ||
{:ok, HTTPoison.Response.t() | HTTPoison.AsyncResponse.t()} | ||
| {:error, HTTPoison.Error.t()} | ||
@callback post(String.t(), any, HTTPoison.Base.headers(), Keyword.t()) :: | ||
{:ok, HTTPoison.Response.t() | HTTPoison.AsyncResponse.t()} | ||
| {:error, HTTPoison.Error.t()} | ||
@callback put(String.t(), any, HTTPoison.Base.headers(), Keyword.t()) :: | ||
{:ok, HTTPoison.Response.t() | HTTPoison.AsyncResponse.t()} | ||
| {:error, HTTPoison.Error.t()} | ||
@callback patch(String.t(), any, HTTPoison.Base.headers(), Keyword.t()) :: | ||
{:ok, HTTPoison.Response.t() | HTTPoison.AsyncResponse.t()} | ||
| {:error, HTTPoison.Error.t()} | ||
end |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks like this has been generalized, and the doc should be updated