From 3d154897a7d9e49d589b964a6e370e55d852a5ee Mon Sep 17 00:00:00 2001 From: njms Date: Wed, 14 Jun 2023 10:12:28 -0700 Subject: [PATCH] Complete token api implementation --- .../controllers/auth/token_controller.ex | 29 +++++++++++++++---- .../auth/token_controller_test.exs | 6 ++-- 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/lib/hostas_web/controllers/auth/token_controller.ex b/lib/hostas_web/controllers/auth/token_controller.ex index c0d4a5a..099e538 100644 --- a/lib/hostas_web/controllers/auth/token_controller.ex +++ b/lib/hostas_web/controllers/auth/token_controller.ex @@ -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 diff --git a/test/hostas_web/controllers/auth/token_controller_test.exs b/test/hostas_web/controllers/auth/token_controller_test.exs index 1a0c82e..dd86417 100644 --- a/test/hostas_web/controllers/auth/token_controller_test.exs +++ b/test/hostas_web/controllers/auth/token_controller_test.exs @@ -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