feat(admin): rebuild admin panel as out-of-band login with backups
- Separate admin login (ADMIN_USERNAME/ADMIN_PASSWORD) with its own JWT, no longer a seeded user account; lockout after 5 failed attempts - Admin panel tabs: Users, Notifications, Backups, Reset - Ntfy settings moved from .env/compose into admin_settings (token encrypted) - Scheduled and on-demand mariadb-dump backups to NFS volume, with restore (entries only or all) and retention pruning - Reset all entries, guarded by an automatic safety backup - Remove user impersonation and the admin link in the user nav - Login page falls back to admin login; nginx sends Cache-Control: no-cache Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
c54d2b251f
commit
6272322f31
28 files changed
+1523
-461
No files matched your search
@@ -0,0 +1,21 @@
|
||||
import base64
|
||||
import hashlib
|
||||
|
||||
from cryptography.fernet import Fernet
|
||||
|
||||
from app.config import settings
|
||||
|
||||
|
||||
def _fernet() -> Fernet:
|
||||
# Derived from SECRET_KEY: rotating SECRET_KEY also invalidates any
|
||||
# previously encrypted values (e.g. the stored ntfy token).
|
||||
key = hashlib.sha256(settings.secret_key.encode()).digest()
|
||||
return Fernet(base64.urlsafe_b64encode(key))
|
||||
|
||||
|
||||
def encrypt(value: str) -> str:
|
||||
return _fernet().encrypt(value.encode()).decode()
|
||||
|
||||
|
||||
def decrypt(value: str) -> str:
|
||||
return _fernet().decrypt(value.encode()).decode()
|
||||
+62
-12
@@ -1,19 +1,69 @@
|
||||
import base64
|
||||
import logging
|
||||
import httpx
|
||||
from typing import Optional
|
||||
|
||||
from app.config import settings
|
||||
import httpx
|
||||
from cryptography.fernet import InvalidToken
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.database import AsyncSessionLocal
|
||||
from app.utils.crypto import decrypt
|
||||
|
||||
logger = logging.getLogger("bourbonacci.notify")
|
||||
|
||||
|
||||
async def notify(title: str, message: str, priority: str = "default") -> None:
|
||||
if not settings.ntfy_url:
|
||||
return
|
||||
headers = {"Title": f"Bourbonacci Admin - {title}", "Priority": priority}
|
||||
if settings.ntfy_token:
|
||||
headers["Authorization"] = f"Bearer {settings.ntfy_token}"
|
||||
def _header_value(value: str) -> str:
|
||||
# HTTP header values must be ASCII; ntfy decodes RFC 2047 encoded-words,
|
||||
# so send non-ASCII titles/tags that way and leave plain ASCII untouched.
|
||||
if value.isascii():
|
||||
return value
|
||||
return "=?UTF-8?B?" + base64.b64encode(value.encode("utf-8")).decode("ascii") + "?="
|
||||
|
||||
|
||||
def _normalize_server_url(server_url: str) -> str:
|
||||
server_url = server_url.strip()
|
||||
if not server_url.startswith(("http://", "https://")):
|
||||
server_url = "https://" + server_url
|
||||
return server_url
|
||||
|
||||
|
||||
async def notify(
|
||||
title: str,
|
||||
message: str,
|
||||
priority: str = "default",
|
||||
tags: Optional[list[str]] = None,
|
||||
) -> bool:
|
||||
"""Send an admin push notification using the ntfy settings saved in the
|
||||
admin panel (Notifications tab). Returns False if not configured or the
|
||||
send failed; never raises."""
|
||||
from app.models.admin_settings import AdminSettings
|
||||
|
||||
async with AsyncSessionLocal() as db:
|
||||
row = (await db.execute(select(AdminSettings).where(AdminSettings.id == 1))).scalar_one_or_none()
|
||||
if not row or not row.ntfy_server_url or not row.ntfy_topic:
|
||||
return False
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=5) as client:
|
||||
await client.post(settings.ntfy_url, content=message, headers=headers)
|
||||
except Exception as exc:
|
||||
logger.warning("Ntfy notification failed: %s", exc)
|
||||
token = decrypt(row.ntfy_token) if row.ntfy_token else None
|
||||
except InvalidToken:
|
||||
logger.error("Could not decrypt stored admin ntfy token")
|
||||
return False
|
||||
|
||||
server_url = _normalize_server_url(row.ntfy_server_url)
|
||||
url = server_url.rstrip("/") + "/" + row.ntfy_topic.strip("/")
|
||||
headers = {"Title": _header_value(f"Bourbonacci Admin - {title}"), "Priority": priority}
|
||||
if tags:
|
||||
headers["Tags"] = _header_value(",".join(tags))
|
||||
if token:
|
||||
headers["Authorization"] = f"Bearer {token}"
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
resp = await client.post(url, content=message.encode("utf-8"), headers=headers)
|
||||
if resp.status_code >= 300:
|
||||
logger.warning("Ntfy send to %s failed with status %s", server_url, resp.status_code)
|
||||
return False
|
||||
return True
|
||||
except httpx.HTTPError as exc:
|
||||
logger.warning("Ntfy send to %s failed: %s", server_url, exc)
|
||||
return False
|
||||
@@ -17,14 +17,18 @@ def verify_password(plain: str, hashed: str) -> bool:
|
||||
return pwd_context.verify(plain, hashed)
|
||||
|
||||
|
||||
def create_token(user_id: int, admin_id: Optional[int] = None) -> str:
|
||||
def create_token(user_id: int) -> str:
|
||||
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes)
|
||||
payload: dict = {"sub": str(user_id), "exp": expire}
|
||||
if admin_id is not None:
|
||||
payload["admin_id"] = admin_id
|
||||
return jwt.encode(payload, settings.secret_key, algorithm=settings.algorithm)
|
||||
|
||||
|
||||
def create_admin_token() -> str:
|
||||
# No "sub" claim, so decode_token() rejects it as a user token.
|
||||
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes)
|
||||
return jwt.encode({"admin": True, "exp": expire}, settings.secret_key, algorithm=settings.algorithm)
|
||||
|
||||
|
||||
def decode_token(token: str) -> Optional[int]:
|
||||
try:
|
||||
payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
|
||||
@@ -36,8 +40,9 @@ def decode_token(token: str) -> Optional[int]:
|
||||
return None
|
||||
|
||||
|
||||
def decode_token_full(token: str) -> Optional[dict]:
|
||||
def is_admin_token(token: str) -> bool:
|
||||
try:
|
||||
return jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
|
||||
payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
|
||||
except JWTError:
|
||||
return None
|
||||
return False
|
||||
return payload.get("admin") is True
|
||||
Reference in new issue
Block a user