defmodule PinchflatWeb.ApiAuthPlug do @moduledoc """ Authenticates API requests using a Bearer token. The token is read from the `PINCHFLAT_API_TOKEN` environment variable. If the environment variable is not set, API authentication is disabled (useful for development and testing). In production, you should always set this to a secure value. Clients should send the token in the Authorization header: Authorization: Bearer """ import Plug.Conn def init(opts), do: opts def call(conn, _opts) do expected_token = Application.get_env(:pinchflat, :api_token) if credential_set?(expected_token) do case get_req_header(conn, "authorization") do ["Bearer " <> token] -> if String.trim(token) == expected_token do conn else send_unauthorized(conn) end _ -> send_unauthorized(conn) end else # No API token configured — allow access (dev/test mode) conn end end defp credential_set?(credential) do credential && credential != "" end defp send_unauthorized(conn) do conn |> put_resp_content_type("application/json") |> send_resp(401, ~s({"errors":{"detail":"Unauthorized"}})) |> halt() end end