Skip to content
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

Support Twilio API key-based authentication #173

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions lib/ex_twilio/api.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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 """
Expand Down
24 changes: 24 additions & 0 deletions test/ex_twilio/api_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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
###
Expand Down