Make API auth mandatory, manage tokens via web UI
BREAKING CHANGE: API authentication is now always required. The PINCHFLAT_API_TOKEN env var is no longer used. Instead, tokens are stored in the database and managed via Settings → API Access. Changes: - Add api_token column to settings table (migration) - ApiAuthPlug reads from DB; returns 401 if no token configured - Add API Access section to Settings page with generate/regenerate/revoke - Add POST /settings/generate_api_token and /settings/revoke_api_token - Remove api_token from config.exs and runtime.exs - Update all API controller tests to set auth token in setup - Update auth plug tests for mandatory authentication - 1008 tests pass, zero warnings
This commit is contained in:
@@ -2,21 +2,21 @@ 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.
|
||||
The token is stored in the settings database and managed via the web UI.
|
||||
A token must be generated before API access is possible — the API is
|
||||
always authenticated, there is no open-access mode.
|
||||
|
||||
Clients should send the token in the Authorization header:
|
||||
Authorization: Bearer <token>
|
||||
"""
|
||||
|
||||
import Plug.Conn
|
||||
alias Pinchflat.Settings
|
||||
|
||||
def init(opts), do: opts
|
||||
|
||||
def call(conn, _opts) do
|
||||
expected_token = Application.get_env(:pinchflat, :api_token)
|
||||
expected_token = Settings.get!(:api_token)
|
||||
|
||||
if credential_set?(expected_token) do
|
||||
case get_req_header(conn, "authorization") do
|
||||
@@ -31,8 +31,8 @@ defmodule PinchflatWeb.ApiAuthPlug do
|
||||
send_unauthorized(conn)
|
||||
end
|
||||
else
|
||||
# No API token configured — allow access (dev/test mode)
|
||||
conn
|
||||
# No API token has been generated yet — deny all access
|
||||
send_unauthorized(conn, "API token not configured. Generate one in Settings.")
|
||||
end
|
||||
end
|
||||
|
||||
@@ -40,10 +40,10 @@ defmodule PinchflatWeb.ApiAuthPlug do
|
||||
credential && credential != ""
|
||||
end
|
||||
|
||||
defp send_unauthorized(conn) do
|
||||
defp send_unauthorized(conn, message \\ "Unauthorized") do
|
||||
conn
|
||||
|> put_resp_content_type("application/json")
|
||||
|> send_resp(401, ~s({"errors":{"detail":"Unauthorized"}}))
|
||||
|> send_resp(401, ~s({"errors":{"detail":"#{message}"}}))
|
||||
|> halt()
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user