- Add jump_credo_checks ~> 0.4 with all 20 checks enabled - Fix all standard Credo issues: 139 @spec (113 done, 26 remain), 4 refactoring, 3 alias usage, 9 System.cmd env, 5 unsafe_to_atom, 2 max line length, 9 assert_receive timeout - Fix 170+ jump_credo_checks warnings: - 117 TopLevelAliasImportRequire: move nested alias/import to module top - 32 UseObanProWorker: switch to Oban.Pro.Worker - 4 DoctestIExExamples: add doctests / create test file - ~20 WeakAssertion: strengthen type-check assertions - Various ConditionalAssertion, AssertReceiveTimeout fixes - Exclude vendor/ from Credo analysis - Remaining: 175 warnings (mostly opinionated WeakAssertion, AvoidSocketAssignsInTest), 26 @spec annotations
48 lines
1.5 KiB
Elixir
48 lines
1.5 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
|
|
|
|
@spec create(Plug.Conn.t(), map()) :: Plug.Conn.t()
|
|
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
|
|
|
|
@spec delete(Plug.Conn.t(), map()) :: Plug.Conn.t()
|
|
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
|