prop/lib/microwaveprop_web/api/fallback_controller.ex
Graham McIntire c6d2c48264
feat: secure /api/v1 REST API for regular-user actions
Adds bearer-token authenticated REST API at /api/v1 covering every
action a non-admin user can perform on the website: contact + beacon
submission, beacon-monitor management, propagation queries, profile
read/update, and self-service API token issuance/revocation.

Security: SHA-256-hashed bearer tokens (mwp_ prefix, plaintext shown
once at creation), RFC 9457 problem+json error responses, RFC 9651
RateLimit-* headers backed by an ETS bucket (600/min per token,
60/min per anonymous IP, 30/min on /auth/tokens), private-contact
filtering by viewer.

Docs at docs/api/README.md (prose reference) and docs/api/openapi.yaml
(OpenAPI 3.1 spec covering every endpoint, response, and schema).

Tests: 124 new tests across schema, plug, error renderer, rate
limiter, fallback, and every controller. 16/17 API modules at 100%
line coverage; FallbackController at 87.5% (one defmodule line, an
Erlang-cover artifact for action_fallback-only modules).
2026-05-09 08:59:54 -05:00

35 lines
1.1 KiB
Elixir

defmodule MicrowavepropWeb.Api.FallbackController do
@moduledoc """
Translates `{:error, term}` tuples returned from `/api/v1` controller
actions into RFC 9457 problem+json responses. Wired via
`action_fallback/1` in `MicrowavepropWeb.Api.V1.BaseController`.
"""
use Phoenix.Controller, formats: [:json]
alias MicrowavepropWeb.Api.ErrorJSON
def call(conn, {:error, %Ecto.Changeset{} = changeset}) do
ErrorJSON.send_changeset(conn, changeset)
end
def call(conn, {:error, :not_found}) do
ErrorJSON.send_problem(conn, 404, "not_found", "Resource not found.")
end
def call(conn, {:error, :forbidden}) do
ErrorJSON.send_problem(conn, 403, "forbidden", "You may not access this resource.")
end
def call(conn, {:error, :unauthorized}) do
ErrorJSON.send_problem(conn, 401, "unauthorized", "Authentication is required.")
end
def call(conn, {:error, :bad_request, detail}) when is_binary(detail) do
ErrorJSON.send_problem(conn, 400, "bad_request", detail)
end
def call(conn, {:error, :duplicate, _existing}) do
ErrorJSON.send_problem(conn, 409, "conflict", "An equivalent resource already exists.")
end
end