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).
52 lines
1.4 KiB
Elixir
52 lines
1.4 KiB
Elixir
defmodule MicrowavepropWeb.Api.V1.BeaconController do
|
|
@moduledoc "Read approved beacons; submit new beacons (pending approval)."
|
|
|
|
use Phoenix.Controller, formats: [:json]
|
|
|
|
alias Microwaveprop.Beacons
|
|
alias MicrowavepropWeb.Api.ErrorJSON
|
|
alias MicrowavepropWeb.Api.V1.BeaconJSON
|
|
|
|
plug :accepts, ["json"]
|
|
action_fallback MicrowavepropWeb.Api.FallbackController
|
|
|
|
def index(conn, _params) do
|
|
beacons = Beacons.list_beacons()
|
|
json(conn, BeaconJSON.index(%{beacons: beacons}))
|
|
end
|
|
|
|
def show(conn, %{"id" => id}) do
|
|
case fetch_beacon(id) do
|
|
nil -> ErrorJSON.send_problem(conn, 404, "not_found", "Beacon not found.")
|
|
beacon -> json(conn, BeaconJSON.show(%{beacon: beacon}))
|
|
end
|
|
end
|
|
|
|
def create(conn, params) do
|
|
user = conn.assigns.current_api_user
|
|
|
|
attrs =
|
|
Map.take(
|
|
params,
|
|
~w(frequency_mhz callsign grid lat lon power_mw height_ft on_the_air keying bearing beamwidth_deg notes)
|
|
)
|
|
|
|
case Beacons.create_beacon(user, attrs) do
|
|
{:ok, beacon} ->
|
|
conn
|
|
|> put_status(:created)
|
|
|> json(BeaconJSON.show(%{beacon: beacon}))
|
|
|
|
{:error, changeset} ->
|
|
ErrorJSON.send_changeset(conn, changeset)
|
|
end
|
|
end
|
|
|
|
# `Beacons.get_beacon!/1` raises on bad ids; we want a clean 404.
|
|
defp fetch_beacon(id) do
|
|
Beacons.get_beacon!(id)
|
|
rescue
|
|
Ecto.NoResultsError -> nil
|
|
Ecto.Query.CastError -> nil
|
|
end
|
|
end
|