diff --git a/lib/ex_twilio/api.ex b/lib/ex_twilio/api.ex index 408e61a..3935f53 100644 --- a/lib/ex_twilio/api.ex +++ b/lib/ex_twilio/api.ex @@ -128,19 +128,28 @@ defmodule ExTwilio.Api do end @doc """ - Builds custom auth header for subaccounts. + Builds custom auth header for subaccounts or API key-based auth. ## Examples iex> ExTwilio.Api.auth_header([account: 123, token: 123]) ["Authorization": "Basic MTIzOjEyMw=="] + iex> ExTwilio.Api.auth_header([api_key: SK1, api_secret: 456]) + ["Authorization": "Basic RWxpeGlyLlNLMTo0NTY="] + iex> ExTwilio.Api.auth_header([], {nil, 2}) [] """ @spec auth_header(options :: list) :: list def auth_header(options \\ []) do - auth_header([], {options[:account], options[:token]}) + case Keyword.has_key?(options, :api_key) and Keyword.has_key?(options, :api_secret) do + true -> + auth_header([], {options[:api_key], options[:api_secret]}) + + false -> + auth_header([], {options[:account], options[:token]}) + end end @doc """ diff --git a/test/ex_twilio/api_test.exs b/test/ex_twilio/api_test.exs index a1b6497..4819d4f 100644 --- a/test/ex_twilio/api_test.exs +++ b/test/ex_twilio/api_test.exs @@ -87,6 +87,30 @@ defmodule ExTwilio.ApiTest do end) end + test ".auth_header returns no headers by default" do + assert [] == Api.auth_header([]) + end + + test ".auth_header with account and token options generates an account-level HTTP BASIC Authorization header" do + account = "AC-testsid" + token = "test-account-token" + encoded = Base.encode64("#{account}:#{token}") + basic_header = "Basic #{encoded}" + assert [Authorization: basic_header] == Api.auth_header([account: account, token: token]) + end + + test ".auth_header with api_key and api_secret options generates an API key-level HTTP BASIC Authorization header" do + api_key = "SK-testkey" + api_secret = "test-api-secret" + encoded = Base.encode64("#{api_key}:#{api_secret}") + basic_header = "Basic #{encoded}" + assert [Authorization: basic_header] == Api.auth_header([api_key: api_key, api_secret: api_secret]) + end + + test ".auth_header with an existing Authorization header retains the existing header" do + assert [Authorization: "BASIC existing"] == Api.auth_header([Authorization: "BASIC existing"], {"sid", "token"}) + end + ### # HTTPoison API ###