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.
46 lines
1.4 KiB
Elixir
46 lines
1.4 KiB
Elixir
defmodule MicrowavepropWeb.ApiTokenController do
|
|
@moduledoc """
|
|
User-facing CRUD for long-lived `/api/v1` bearer tokens. The plaintext
|
|
token 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.
|
|
"""
|
|
|
|
use MicrowavepropWeb, :controller
|
|
|
|
alias Microwaveprop.Accounts
|
|
|
|
def create(conn, %{"api_token" => params}) do
|
|
user = conn.assigns.current_scope.user
|
|
|
|
case Accounts.create_api_token(user, params) do
|
|
{:ok, {plaintext, record}} ->
|
|
conn
|
|
|> put_flash(:info, "API token '#{record.name}' created. Copy it now — it is shown once.")
|
|
|> put_flash(:api_token, plaintext)
|
|
|> redirect(to: ~p"/users/settings")
|
|
|
|
{:error, changeset} ->
|
|
message =
|
|
changeset
|
|
|> Ecto.Changeset.traverse_errors(fn {msg, _} -> msg end)
|
|
|> Enum.map_join("; ", fn {k, v} -> "#{k}: #{Enum.join(v, ", ")}" end)
|
|
|
|
conn
|
|
|> put_flash(:error, "Could not create API token (#{message}).")
|
|
|> redirect(to: ~p"/users/settings")
|
|
end
|
|
end
|
|
|
|
def delete(conn, %{"id" => id}) do
|
|
user = conn.assigns.current_scope.user
|
|
|
|
conn =
|
|
case Accounts.revoke_api_token(user, id) do
|
|
{:ok, _token} -> put_flash(conn, :info, "API token revoked.")
|
|
{:error, :not_found} -> put_flash(conn, :error, "API token not found.")
|
|
end
|
|
|
|
redirect(conn, to: ~p"/users/settings")
|
|
end
|
|
end
|