Complete token api implementation
This commit is contained in:
parent
9657ab818c
commit
3d154897a7
|
@ -62,8 +62,7 @@ defmodule HostasWeb.Auth.TokenController do
|
|||
"""
|
||||
def revoke(conn, %{"id" => id_param}) do
|
||||
with {:parsed_id, {id, ""}} <- {:parsed_id, Integer.parse(id_param, 10)},
|
||||
{:ok, token} <- fetch_token(id, conn),
|
||||
{:can_access, true} <- {:can_access, token.denizen_id == conn.assigns[:denizen].id} do
|
||||
{:ok, token} <- fetch_token(id, conn) do
|
||||
Repo.delete_all(from t in Token, where: t.id == ^token.id)
|
||||
|
||||
conn
|
||||
|
@ -80,8 +79,22 @@ defmodule HostasWeb.Auth.TokenController do
|
|||
Deletes the token the requester used in the `Bearing` header
|
||||
and responds with a new one if the old one was valid and unexpired
|
||||
"""
|
||||
def renew(_conn, _params) do
|
||||
:ok
|
||||
def renew(conn, %{"id" => id_param}) do
|
||||
with {:parsed_id, {id, ""}} <- {:parsed_id, Integer.parse(id_param, 10)},
|
||||
{:ok, token} <- fetch_token(id, conn) do
|
||||
Repo.delete_all(from t in Token, where: t.id == ^token.id)
|
||||
|
||||
{:ok, new_token} = Token.new(conn.assigns[:denizen].id)
|
||||
|
||||
conn
|
||||
|> put_status(201)
|
||||
|> json(Map.take(new_token, [:token, :expires]))
|
||||
else
|
||||
_ ->
|
||||
conn
|
||||
|> put_status(404)
|
||||
|> json(%{"error" => "Token not found"})
|
||||
end
|
||||
end
|
||||
|
||||
defp fetch_token(id, conn) do
|
||||
|
@ -90,7 +103,13 @@ defmodule HostasWeb.Auth.TokenController do
|
|||
else
|
||||
case Repo.one(from t in Token, where: t.id == ^id) do
|
||||
nil -> {:error, :token_not_found}
|
||||
token -> {:ok, token}
|
||||
token ->
|
||||
# If the denizen doesn't own it, we lie about its existence
|
||||
if token.denizen_id == conn.assigns[:denizen].id do
|
||||
{:ok, token}
|
||||
else
|
||||
{:error, :token_not_found}
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
|
@ -117,10 +117,10 @@ defmodule HostasWeb.Auth.TokenControllerTest do
|
|||
conn =
|
||||
conn
|
||||
|> put_req_header("authorization", "Bearer #{struct.token}")
|
||||
|> get(~p"/hostapi/auth/token/${struct.id}/renew")
|
||||
|> get(~p"/hostapi/auth/token/#{struct.id}/renew")
|
||||
|
||||
assert Map.has_key?(json_response(conn, 200), "token")
|
||||
assert Map.has_key?(json_response(conn, 200), "expires")
|
||||
assert Map.has_key?(json_response(conn, 201), "token")
|
||||
assert Map.has_key?(json_response(conn, 201), "expires")
|
||||
assert not Repo.exists?(from t in Token, where: t.id == ^struct.id)
|
||||
end
|
||||
|
||||
|
|
Loading…
Reference in New Issue