feat: settings UI (admin-only, live-updates app.config)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-18 20:35:39 -04:00
parent c5dff7ec8c
commit dfb433e779
4 changed files with 270 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
# fablednetmon/settings/__init__.py
+142
View File
@@ -0,0 +1,142 @@
# fablednetmon/settings/routes.py
from __future__ import annotations
import json
import logging
from pathlib import Path
from quart import Blueprint, current_app, render_template, request, redirect, url_for
from fablednetmon.auth.middleware import require_role
from fablednetmon.models.users import UserRole
from fablednetmon.core.settings import (
DEFAULTS, get_all_settings, set_setting,
to_smtp_cfg, to_webhook_cfg, to_ansible_cfg, to_plugins_cfg,
)
settings_bp = Blueprint("settings", __name__, url_prefix="/settings")
logger = logging.getLogger(__name__)
def _discover_plugins() -> list[dict]:
"""Scan PLUGIN_DIR for plugin.yaml files. Returns list of plugin metadata dicts."""
import yaml
plugin_dir = Path(current_app.config.get("PLUGIN_DIR", "plugins")).resolve()
plugins = []
if not plugin_dir.exists():
return plugins
for entry in sorted(plugin_dir.iterdir()):
yaml_path = entry / "plugin.yaml"
if entry.is_dir() and yaml_path.exists():
try:
with yaml_path.open() as f:
meta = yaml.safe_load(f) or {}
meta["_dir"] = entry.name
plugins.append(meta)
except Exception:
logger.warning("Could not read %s", yaml_path)
return plugins
@settings_bp.get("/")
@require_role(UserRole.admin)
async def index():
async with current_app.db_sessionmaker() as db:
settings = await get_all_settings(db)
discovered_plugins = _discover_plugins()
# Merge current plugin settings from DB into discovered plugin list
plugins_cfg = to_plugins_cfg(settings)
for plugin in discovered_plugins:
name = plugin["_dir"]
stored = plugins_cfg.get(name, {})
plugin["_enabled"] = stored.get("enabled", False)
# Merge config defaults with stored overrides for display
defaults = plugin.get("config", {})
plugin["_config"] = {**defaults, **{k: v for k, v in stored.items() if k != "enabled"}}
return await render_template(
"settings/index.html",
settings=settings,
discovered_plugins=discovered_plugins,
)
@settings_bp.post("/")
@require_role(UserRole.admin)
async def save():
form = await request.form
async with current_app.db_sessionmaker() as db:
async with db.begin():
# General settings
await set_setting(db, "session.lifetime_hours",
int(form.get("session.lifetime_hours", 8)))
await set_setting(db, "data.retention_days",
int(form.get("data.retention_days", 90)))
await set_setting(db, "monitors.poll_interval_seconds",
int(form.get("monitors.poll_interval_seconds", 60)))
# SMTP
recipients_raw = form.get("smtp.recipients", "")
recipients = [r.strip() for r in recipients_raw.split(",") if r.strip()]
await set_setting(db, "smtp.host", form.get("smtp.host", ""))
await set_setting(db, "smtp.port", int(form.get("smtp.port", 587)))
await set_setting(db, "smtp.tls", "smtp.tls" in form)
await set_setting(db, "smtp.username", form.get("smtp.username", ""))
if form.get("smtp.password"):
await set_setting(db, "smtp.password", form.get("smtp.password"))
await set_setting(db, "smtp.recipients", recipients)
# Webhook
await set_setting(db, "webhook.url", form.get("webhook.url", ""))
await set_setting(db, "webhook.template", form.get("webhook.template", ""))
# Ansible sources (JSON textarea)
sources_raw = form.get("ansible.sources", "[]")
try:
sources = json.loads(sources_raw)
if not isinstance(sources, list):
sources = []
except json.JSONDecodeError:
sources = []
await set_setting(db, "ansible.sources", sources)
# Build per-plugin config dicts from form fields
discovered = _discover_plugins()
for plugin in discovered:
name = plugin["_dir"]
enabled = f"plugin.{name}.enabled" in form
plugin_cfg: dict = {"enabled": enabled}
for cfg_key in plugin.get("config", {}).keys():
field_name = f"plugin.{name}.{cfg_key}"
if field_name in form:
raw_val = form[field_name]
# Coerce to the default type
default_val = plugin["config"][cfg_key]
if isinstance(default_val, bool):
plugin_cfg[cfg_key] = raw_val.lower() in ("1", "true", "yes", "on")
elif isinstance(default_val, int):
try:
plugin_cfg[cfg_key] = int(raw_val)
except ValueError:
plugin_cfg[cfg_key] = default_val
else:
plugin_cfg[cfg_key] = raw_val
await set_setting(db, f"plugin.{name}", plugin_cfg)
# Live-update app.config so settings take effect without restart
from fablednetmon.core.settings import get_all_settings as _get_all
async with current_app.db_sessionmaker() as db:
fresh = await _get_all(db)
current_app.config.update(
SESSION_LIFETIME_HOURS=fresh.get("session.lifetime_hours", 8),
DATA_RETENTION_DAYS=fresh.get("data.retention_days", 90),
MONITORS_POLL_INTERVAL=fresh.get("monitors.poll_interval_seconds", 60),
SMTP=to_smtp_cfg(fresh),
WEBHOOK=to_webhook_cfg(fresh),
ANSIBLE=to_ansible_cfg(fresh),
PLUGINS=to_plugins_cfg(fresh),
)
return redirect(url_for("settings.index"))
+3
View File
@@ -37,6 +37,9 @@
<a href="/hosts/">Hosts</a>
<a href="/alerts/">Alerts</a>
<a href="/ansible/">Ansible</a>
{% if session.user_role == 'admin' %}
<a href="/settings/">Settings</a>
{% endif %}
<a href="/logout">Logout ({{ session.username }})</a>
</nav>
{% endif %}
+124
View File
@@ -0,0 +1,124 @@
{# fablednetmon/templates/settings/index.html #}
{% extends "base.html" %}
{% block title %}Settings — FabledNetMon{% endblock %}
{% block content %}
<h1 style="color:#c0c0ff;margin-bottom:1.5rem;">Settings</h1>
<form method="post" action="/settings/">
<div style="display:grid;gap:1.5rem;">
{# ── General ──────────────────────────────────────────────────────────── #}
<div class="card">
<h2 style="color:#8080ff;margin-bottom:1rem;font-size:1rem;">General</h2>
<div class="form-group">
<label>Session lifetime (hours)</label>
<input type="number" name="session.lifetime_hours" min="1" max="720"
value="{{ settings['session.lifetime_hours'] }}">
</div>
<div class="form-group">
<label>Data retention (days)</label>
<input type="number" name="data.retention_days" min="1"
value="{{ settings['data.retention_days'] }}">
</div>
<div class="form-group">
<label>Monitor poll interval (seconds)</label>
<input type="number" name="monitors.poll_interval_seconds" min="10"
value="{{ settings['monitors.poll_interval_seconds'] }}">
</div>
</div>
{# ── SMTP ─────────────────────────────────────────────────────────────── #}
<div class="card">
<h2 style="color:#8080ff;margin-bottom:1rem;font-size:1rem;">Email (SMTP)</h2>
<div class="form-group">
<label>SMTP host</label>
<input type="text" name="smtp.host" value="{{ settings['smtp.host'] }}" placeholder="mail.example.com">
</div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
<div class="form-group">
<label>Port</label>
<input type="number" name="smtp.port" value="{{ settings['smtp.port'] }}">
</div>
<div class="form-group" style="display:flex;align-items:center;gap:0.5rem;padding-top:1.5rem;">
<input type="checkbox" name="smtp.tls" id="smtp-tls"
{% if settings['smtp.tls'] %}checked{% endif %}>
<label for="smtp-tls" style="margin:0;">Use TLS</label>
</div>
</div>
<div class="form-group">
<label>Username</label>
<input type="text" name="smtp.username" value="{{ settings['smtp.username'] }}" autocomplete="off">
</div>
<div class="form-group">
<label>Password <span style="color:#606080;font-size:0.8rem;">(leave blank to keep current)</span></label>
<input type="password" name="smtp.password" placeholder="••••••••" autocomplete="new-password">
</div>
<div class="form-group">
<label>Recipients <span style="color:#606080;font-size:0.8rem;">(comma-separated)</span></label>
<input type="text" name="smtp.recipients"
value="{{ settings['smtp.recipients'] | join(', ') }}"
placeholder="admin@example.com, ops@example.com">
</div>
</div>
{# ── Webhook ──────────────────────────────────────────────────────────── #}
<div class="card">
<h2 style="color:#8080ff;margin-bottom:1rem;font-size:1rem;">Webhook</h2>
<div class="form-group">
<label>Webhook URL <span style="color:#606080;font-size:0.8rem;">(leave blank to disable)</span></label>
<input type="text" name="webhook.url" value="{{ settings['webhook.url'] }}"
placeholder="https://discord.com/api/webhooks/...">
</div>
<div class="form-group">
<label>Payload template <span style="color:#606080;font-size:0.8rem;">(Jinja2, must produce valid JSON)</span></label>
<textarea name="webhook.template" rows="3"
style="width:100%;background:#0f0f1e;border:1px solid #3a3a5a;border-radius:4px;color:#e0e0e0;padding:0.5rem;font-family:monospace;font-size:0.85rem;">{{ settings['webhook.template'] }}</textarea>
</div>
</div>
{# ── Ansible Sources ──────────────────────────────────────────────────── #}
<div class="card">
<h2 style="color:#8080ff;margin-bottom:1rem;font-size:1rem;">Ansible Sources</h2>
<p style="color:#606080;font-size:0.85rem;margin-bottom:0.75rem;">JSON array of source objects. Each requires <code>name</code>, <code>type</code> (git or local), and either <code>url</code> or <code>path</code>.</p>
<textarea name="ansible.sources" rows="8"
style="width:100%;background:#0f0f1e;border:1px solid #3a3a5a;border-radius:4px;color:#e0e0e0;padding:0.5rem;font-family:monospace;font-size:0.85rem;">{{ settings['ansible.sources'] | tojson(indent=2) }}</textarea>
</div>
{# ── Plugins ──────────────────────────────────────────────────────────── #}
{% if discovered_plugins %}
<div class="card">
<h2 style="color:#8080ff;margin-bottom:1rem;font-size:1rem;">Plugins</h2>
{% for plugin in discovered_plugins %}
<div style="border:1px solid #2a2a4a;border-radius:4px;padding:1rem;margin-bottom:0.75rem;">
<div style="display:flex;align-items:center;gap:0.75rem;margin-bottom:0.75rem;">
<input type="checkbox" name="plugin.{{ plugin._dir }}.enabled"
id="plugin-{{ plugin._dir }}-enabled"
{% if plugin._enabled %}checked{% endif %}>
<label for="plugin-{{ plugin._dir }}-enabled"
style="margin:0;font-weight:bold;color:#c0c0e0;">
{{ plugin.get('name', plugin._dir) }}
<span style="color:#606080;font-size:0.8rem;font-weight:normal;">
v{{ plugin.get('version', '?') }} — {{ plugin.get('description', '') }}
</span>
</label>
</div>
{% for cfg_key, cfg_default in plugin.get('config', {}).items() %}
<div class="form-group" style="margin-left:1.5rem;">
<label style="font-size:0.85rem;">{{ cfg_key }}</label>
<input type="text" name="plugin.{{ plugin._dir }}.{{ cfg_key }}"
value="{{ plugin._config.get(cfg_key, cfg_default) }}">
</div>
{% endfor %}
</div>
{% endfor %}
</div>
{% endif %}
</div>
<div style="margin-top:1.5rem;">
<button type="submit" class="btn">Save Settings</button>
<span style="color:#606080;font-size:0.85rem;margin-left:1rem;">
Changes take effect immediately. Monitor interval, plugin enable/disable require a restart.
</span>
</div>
</form>
{% endblock %}