Improve OAuth error handling (#10)

* Fixes a crash on network error in access_token!/2 and request_token!/2
* Fixes a crash when an API request results in a non-200 status
This commit is contained in:
Jeff Browning 2016-10-27 11:35:12 -04:00 committed by Sean Callan
parent 8f00575620
commit 97435e8643
3 changed files with 41 additions and 1 deletions

0
config/test.exs Normal file
View File

View File

@ -81,6 +81,8 @@ defmodule Ueberauth.Strategy.Twitter.OAuth do
{:ok, {token, token_secret}} {:ok, {token, token_secret}}
end end
defp decode_access_response({:ok, {{_, status_code, status_description}, _, _}}), do: {:error, "#{status_code} - #{status_description}"}
defp decode_access_response({:error, {error, [_, {:inet, [:inet], error_reason}]}}), do: {:error, "#{error}: #{error_reason}"}
defp decode_access_response(error), do: {:error, error} defp decode_access_response(error), do: {:error, error}
defp decode_request_response({:ok, {{_, 200, _}, _, _} = resp}) do defp decode_request_response({:ok, {{_, 200, _}, _, _} = resp}) do
@ -90,6 +92,8 @@ defmodule Ueberauth.Strategy.Twitter.OAuth do
{:ok, {token, token_secret}} {:ok, {token, token_secret}}
end end
defp decode_request_response({:ok, {{_, status_code, status_description}, _, _}}), do: {:error, "#{status_code} - #{status_description}"}
defp decode_request_response({:error, {error, [_, {:inet, [:inet], error_reason}]}}), do: {:error, "#{error}: #{error_reason}"}
defp decode_request_response(error), do: {:error, error} defp decode_request_response(error), do: {:error, error}
defp endpoint("/" <> _path = endpoint, client), do: client.site <> endpoint defp endpoint("/" <> _path = endpoint, client), do: client.site <> endpoint

View File

@ -0,0 +1,36 @@
defmodule Ueberauth.Strategy.Twitter.OAuthTest do
use ExUnit.Case, async: true
alias Ueberauth.Strategy.Twitter.OAuth
setup do
Application.put_env :ueberauth, OAuth,
consumer_key: "consumer_key",
consumer_secret: "consumer_secret"
:ok
end
test "access_token!/2: raises an appropriate error on auth failure" do
assert_raise RuntimeError, ~r/401/i, fn ->
OAuth.access_token! {"badtoken", "badsecret"}, "badverifier"
end
end
test "access_token!/2 raises an appropriate error on network failure" do
assert_raise RuntimeError, ~r/nxdomain/i, fn ->
OAuth.access_token! {"token", "secret"}, "verifier", site: "https://bogusapi.twitter.com"
end
end
test "request_token!/2: raises an appropriate error on auth failure" do
assert_raise RuntimeError, ~r/401/i, fn ->
OAuth.request_token! [], redirect_uri: "some/uri"
end
end
test "request_token!/2: raises an appropriate error on network failure" do
assert_raise RuntimeError, ~r/nxdomain/i, fn ->
OAuth.request_token! [], site: "https://bogusapi.twitter.com", redirect_uri: "some/uri"
end
end
end