Skip to content

Commit

Permalink
[#43] return token_expired when the JWT token expires
Browse files Browse the repository at this point in the history
  • Loading branch information
ferigis committed Aug 8, 2018
1 parent 11fed68 commit 7d24f68
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 6 deletions.
8 changes: 8 additions & 0 deletions config/prod.exs
Expand Up @@ -59,5 +59,13 @@ config :poa_backend, POABackend.Auth.Guardian,
issuer: "poa_backend",
secret_key: "LQYmeqQfrphbxUjJltkwH4xnosLc+2S2e8KuYWctMenNY9bmgwnrH8r3ii9FP/8V"

# this is a list of admins/passwords for authorisation endpoints
config :poa_backend,
:admins,
[
{"admin1", "password12345678"},
{"admin2", "password87654321"}
]

config :mnesia,
dir: 'priv/data/mnesia' # make sure this directory exists!
4 changes: 3 additions & 1 deletion lib/poa_backend/auth.ex
Expand Up @@ -143,14 +143,16 @@ defmodule POABackend.Auth do
@doc """
Validates if a JWT token is valid.
"""
@spec valid_token?(String.t) :: Boolean.t
@spec valid_token?(String.t) :: Boolean.t | {:error, :token_expired}
def valid_token?(jwt_token) do
with {:ok, claims} <- Auth.Guardian.decode_and_verify(jwt_token),
{:ok, user, ^claims} <- Auth.Guardian.resource_from_token(jwt_token),
true <- user_active?(user)
do
true
else
{:error, :token_expired} = result ->
result
_error -> false
end
end
Expand Down
6 changes: 5 additions & 1 deletion lib/poa_backend/custom_handler/rest/plugs/authorization.ex
Expand Up @@ -17,7 +17,11 @@ defmodule POABackend.CustomHandler.REST.Plugs.Authorization do
do
conn
else
_ ->
{:error, :token_expired} ->
conn
|> send_resp(401, Poison.encode!(%{error: :token_expired}))
|> halt
_error ->
conn
|> send_resp(401, "")
|> halt
Expand Down
19 changes: 15 additions & 4 deletions test/custom_handler/rest_test.exs
Expand Up @@ -242,6 +242,17 @@ defmodule CustomHandler.RESTTest do
assert(original_data == REST.Plugs.RequiredFields.init(original_data))
end

test "get a token_expired response from the backend" do
# create a token which expires in one second
user = Auth.get_user(@user)
{:ok, token, _} = POABackend.Auth.Guardian.encode_and_sign(user, %{}, ttl: {1, :second})

Process.sleep(2000)

assert {:error, :token_expired} == POABackend.Auth.Guardian.decode_and_verify(token)
assert {401, %{"error" => "token_expired"}} == ping("agentID", token)
end

# ----------------------------------------
# Internal functions
# ----------------------------------------
Expand All @@ -254,12 +265,12 @@ defmodule CustomHandler.RESTTest do
defp post(url, data, headers) do
{:ok, response} = HTTPoison.post(url, data, headers)

body = case response.status_code do
200 ->
body = case response.body do
"" ->
:nobody
_ ->
{:ok, body} = Poison.decode(response.body)
body
_ ->
:nobody
end

{response.status_code, body}
Expand Down

0 comments on commit 7d24f68

Please sign in to comment.