Add User-Agent header.

This commit is contained in:
Adam Millerchip 2019-10-02 20:57:20 +09:00
parent 7f94095f3e
commit 5d8f93c8b8
3 changed files with 26 additions and 8 deletions

View File

@ -57,9 +57,16 @@ defmodule LineBot.APIClient do
@doc """
Adds the OAuth Bearer token to the `Authorization` header.
The token is retrieved by calling `LineBot.TokenServer.get_token/0`.
Also adds the `User-Agent` header with a value of `line-botsdk-elixir/vX.X.X`.
This follows the pattern of Line Bot libraries in other languages.
"""
def process_request_headers(headers) do
[{"Authorization", "Bearer #{@token_server.get_token()}"} | super(headers)]
[
{"Authorization", "Bearer #{@token_server.get_token()}"},
{"User-Agent", "line-botsdk-elixir/v#{Application.spec(:line_bot, :vsn)}"}
| super(headers)
]
end
@impl HTTPoison.Base

View File

@ -68,7 +68,12 @@ defmodule LineBot.TokenServer do
%{state | token: token, expires_on: expires_on}
end
@headers [{"Content-Type", "application/x-www-form-urlencoded"}]
defp headers do
[
{"Content-Type", "application/x-www-form-urlencoded"},
{"User-Agent", "line-botsdk-elixir/v#{Application.spec(:line_bot, :vsn)}"}
]
end
defp post_request_token(client_id, client_secret) do
data = [
@ -79,7 +84,7 @@ defmodule LineBot.TokenServer do
%{"access_token" => access_token, "expires_in" => expires_in} =
"https://api.line.me/v2/oauth/accessToken"
|> @http.post!({:form, data}, @headers)
|> @http.post!({:form, data}, headers())
|> Map.get(:body)
|> Jason.decode!()
@ -90,7 +95,7 @@ defmodule LineBot.TokenServer do
@http.post!(
"https://api.line.me/v2/oauth/revoke",
{:form, [access_token: access_token]},
@headers
headers()
)
end

View File

@ -33,14 +33,20 @@ defmodule LineBot.APIClientTest do
assert %{"foo" => "bar"} == APIClient.process_response(response).body
end
test "process_request_headers adds auth header from token server" do
test "process_request_headers adds auth and user-agent headers" do
expect(MockTokenServer, :get_token, fn -> "dummy_token" end)
expect(MockTokenServer, :get_token, fn -> "changed_token" end)
assert [{"Authorization", "Bearer dummy_token"}] == APIClient.process_request_headers([])
assert [
{"Authorization", "Bearer dummy_token"},
{"User-Agent", "line-botsdk-elixir/v" <> _}
] = APIClient.process_request_headers([])
assert [{"Authorization", "Bearer changed_token"}, {"other", "header"}] ==
APIClient.process_request_headers([{"other", "header"}])
assert [
{"Authorization", "Bearer changed_token"},
{"User-Agent", "line-botsdk-elixir/v" <> _},
{"other", "header"}
] = APIClient.process_request_headers([{"other", "header"}])
end
# TODO these call super. Not sure how to test them without calling HTTPoison.