Adds a separate API-token section under /users/settings (distinct from the beacon-monitor token list, since API tokens grant full account access). The plaintext is surfaced exactly once via flash on creation; only the SHA-256 hash is persisted, so revocation is the only path back if the user loses it. Also fixes the openapi.yaml link on /docs/api: the relative path resolved to /docs/openapi.yaml from a no-trailing-slash URL and 404'd.
71 lines
2.3 KiB
Elixir
71 lines
2.3 KiB
Elixir
defmodule MicrowavepropWeb.ApiTokenControllerTest do
|
|
use MicrowavepropWeb.ConnCase, async: true
|
|
|
|
import Microwaveprop.AccountsFixtures
|
|
|
|
alias Microwaveprop.Accounts
|
|
|
|
setup :register_and_log_in_user
|
|
|
|
describe "POST /users/api-tokens" do
|
|
test "creates a token and surfaces the plaintext once via flash", %{conn: conn, user: user} do
|
|
conn =
|
|
post(conn, ~p"/users/api-tokens", %{
|
|
"api_token" => %{"name" => "laptop"}
|
|
})
|
|
|
|
assert redirected_to(conn) == ~p"/users/settings"
|
|
info = Phoenix.Flash.get(conn.assigns.flash, :info)
|
|
assert info =~ "laptop"
|
|
token = Phoenix.Flash.get(conn.assigns.flash, :api_token)
|
|
assert is_binary(token)
|
|
assert String.starts_with?(token, "mwp_")
|
|
|
|
assert [record] = Accounts.list_api_tokens(user)
|
|
assert record.name == "laptop"
|
|
end
|
|
|
|
test "shows an error when name is blank", %{conn: conn, user: user} do
|
|
conn =
|
|
post(conn, ~p"/users/api-tokens", %{
|
|
"api_token" => %{"name" => ""}
|
|
})
|
|
|
|
assert redirected_to(conn) == ~p"/users/settings"
|
|
assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "name"
|
|
assert Accounts.list_api_tokens(user) == []
|
|
end
|
|
|
|
test "redirects unauthenticated users to login" do
|
|
conn =
|
|
post(build_conn(), ~p"/users/api-tokens", %{
|
|
"api_token" => %{"name" => "Nope"}
|
|
})
|
|
|
|
assert redirected_to(conn) == ~p"/users/log-in"
|
|
end
|
|
end
|
|
|
|
describe "DELETE /users/api-tokens/:id" do
|
|
test "revokes a token owned by the current user", %{conn: conn, user: user} do
|
|
{:ok, {_plaintext, record}} = Accounts.create_api_token(user, %{"name" => "bye"})
|
|
|
|
conn = delete(conn, ~p"/users/api-tokens/#{record.id}")
|
|
|
|
assert redirected_to(conn) == ~p"/users/settings"
|
|
assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "revoked"
|
|
assert Accounts.list_api_tokens(user) == []
|
|
end
|
|
|
|
test "does not revoke a token owned by another user", %{conn: conn} do
|
|
other = user_fixture()
|
|
{:ok, {_plaintext, record}} = Accounts.create_api_token(other, %{"name" => "theirs"})
|
|
|
|
conn = delete(conn, ~p"/users/api-tokens/#{record.id}")
|
|
|
|
assert redirected_to(conn) == ~p"/users/settings"
|
|
assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "not found"
|
|
assert [_] = Accounts.list_api_tokens(other)
|
|
end
|
|
end
|
|
end
|