75f75d8d19
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
73 lines
1.9 KiB
Elixir
73 lines
1.9 KiB
Elixir
defmodule PinchflatWeb.Settings.SettingController do
|
|
use PinchflatWeb, :controller
|
|
|
|
alias Pinchflat.Settings
|
|
|
|
def show(conn, _params) do
|
|
setting = Settings.record()
|
|
changeset = Settings.change_setting(setting)
|
|
|
|
render(conn, "show.html", changeset: changeset)
|
|
end
|
|
|
|
def update(conn, %{"setting" => setting_params}) do
|
|
setting = Settings.record()
|
|
|
|
case Settings.update_setting(setting, setting_params) do
|
|
{:ok, _} ->
|
|
conn
|
|
|> put_flash(:info, "Settings updated successfully.")
|
|
|> redirect(to: ~p"/settings")
|
|
|
|
{:error, %Ecto.Changeset{} = changeset} ->
|
|
render(conn, "show.html", changeset: changeset)
|
|
end
|
|
end
|
|
|
|
def app_info(conn, _params) do
|
|
render(conn, "app_info.html")
|
|
end
|
|
|
|
def generate_api_token(conn, _params) do
|
|
token = :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)
|
|
|
|
case Settings.set(api_token: token) do
|
|
{:ok, _} ->
|
|
conn
|
|
|> put_flash(:info, "API token generated successfully.")
|
|
|> redirect(to: ~p"/settings")
|
|
|
|
{:error, _} ->
|
|
conn
|
|
|> put_flash(:error, "Failed to generate API token.")
|
|
|> redirect(to: ~p"/settings")
|
|
end
|
|
end
|
|
|
|
def revoke_api_token(conn, _params) do
|
|
case Settings.set(api_token: nil) do
|
|
{:ok, _} ->
|
|
conn
|
|
|> put_flash(:info, "API token revoked.")
|
|
|> redirect(to: ~p"/settings")
|
|
|
|
{:error, _} ->
|
|
conn
|
|
|> put_flash(:error, "Failed to revoke API token.")
|
|
|> redirect(to: ~p"/settings")
|
|
end
|
|
end
|
|
|
|
def download_logs(conn, _params) do
|
|
log_path = Application.get_env(:pinchflat, :log_path)
|
|
|
|
if log_path && File.exists?(log_path) do
|
|
send_download(conn, {:file, log_path}, filename: "pinchflat-logs-#{Date.utc_today()}.txt")
|
|
else
|
|
conn
|
|
|> put_flash(:error, "Log file couldn't be found")
|
|
|> redirect(to: ~p"/app_info")
|
|
end
|
|
end
|
|
end
|