Files
bourbonacci/backend/app/routers/admin.py
T
derekcandClaude Opus 5.5 6272322f31 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]>
2026-11-23 00:24:19 -08:00

242 lines
8.9 KiB
Python

import secrets
from datetime import datetime, timedelta, timezone
from fastapi import APIRouter, Depends, HTTPException, Request, status
from sqlalchemy import delete, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.dependencies import get_current_admin, get_db
from app.limiter import limiter
from app.models.admin_settings import AdminSettings
from app.models.entry import Entry
from app.models.user import User
from app.schemas.admin import (
AdminLogin,
AdminNtfySettingsOut,
AdminNtfySettingsUpdate,
AdminTokenOut,
AdminUserOut,
ResetPasswordOut,
ResetResultOut,
)
from app.services.backup import BackupError, run_backup
from app.utils.crypto import encrypt
from app.utils.notify import notify
from app.utils.security import create_admin_token, hash_password
router = APIRouter(prefix="/api/admin", tags=["admin"])
MAX_FAILED_ADMIN_ATTEMPTS = 5
ADMIN_LOCKOUT_MINUTES = 15
def _utcnow() -> datetime:
# MySQL DATETIME columns are naive; store UTC.
return datetime.now(timezone.utc).replace(tzinfo=None)
async def _get_admin_settings(db: AsyncSession) -> AdminSettings:
row = (await db.execute(select(AdminSettings).where(AdminSettings.id == 1))).scalar_one_or_none()
if not row:
row = AdminSettings(id=1)
db.add(row)
await db.flush()
return row
@router.post("/login", response_model=AdminTokenOut)
@limiter.limit("5/minute")
async def admin_login(request: Request, body: AdminLogin, db: AsyncSession = Depends(get_db)):
if not settings.admin_username or not settings.admin_password:
raise HTTPException(status_code=503, detail="Admin login is not configured")
row = await _get_admin_settings(db)
if row.admin_locked_until and row.admin_locked_until > _utcnow():
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="Admin login temporarily locked after repeated failed attempts. Try again later.",
)
ok_user = secrets.compare_digest(body.username.encode(), settings.admin_username.encode())
ok_pass = secrets.compare_digest(body.password.encode(), settings.admin_password.encode())
if not (ok_user and ok_pass):
row.admin_failed_attempts += 1
if row.admin_failed_attempts >= MAX_FAILED_ADMIN_ATTEMPTS:
row.admin_locked_until = _utcnow() + timedelta(minutes=ADMIN_LOCKOUT_MINUTES)
row.admin_failed_attempts = 0
await db.commit()
await notify(
"Admin login locked",
f"Admin login was locked out after {MAX_FAILED_ADMIN_ATTEMPTS} failed attempts.",
priority="high",
tags=["warning", "rotating_light"],
)
else:
await db.commit()
raise HTTPException(status_code=401, detail="Invalid admin credentials")
row.admin_failed_attempts = 0
row.admin_locked_until = None
await db.commit()
await notify("Admin login", "Successful admin login.", priority="high", tags=["closed_lock_with_key"])
return AdminTokenOut(access_token=create_admin_token())
# ── Users ────────────────────────────────────────────────────────────────────
@router.get("/users", response_model=list[AdminUserOut], dependencies=[Depends(get_current_admin)])
async def list_users(db: AsyncSession = Depends(get_db)):
rows = (
await db.execute(
select(User, func.count(Entry.id))
.outerjoin(Entry, Entry.user_id == User.id)
.group_by(User.id)
.order_by(func.lower(User.email))
)
).all()
return [
AdminUserOut(
id=u.id,
email=u.email,
display_name=u.display_name,
created_at=u.created_at,
is_disabled=u.is_disabled,
entry_count=count,
)
for u, count in rows
]
async def _get_user(user_id: int, db: AsyncSession) -> User:
user = (await db.execute(select(User).where(User.id == user_id))).scalar_one_or_none()
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
@router.post(
"/users/{user_id}/reset-password",
response_model=ResetPasswordOut,
dependencies=[Depends(get_current_admin)],
)
async def reset_password(user_id: int, db: AsyncSession = Depends(get_db)):
user = await _get_user(user_id, db)
temp_password = secrets.token_urlsafe(9)
user.password_hash = hash_password(temp_password)
await db.commit()
await notify("Password reset issued", f"A temp password was issued for {user.email}.")
return ResetPasswordOut(temp_password=temp_password)
@router.post(
"/users/{user_id}/disable",
status_code=status.HTTP_204_NO_CONTENT,
dependencies=[Depends(get_current_admin)],
)
async def disable_user(user_id: int, db: AsyncSession = Depends(get_db)):
user = await _get_user(user_id, db)
user.is_disabled = True
await db.commit()
await notify("User disabled", f"Account disabled: {user.email}")
@router.post(
"/users/{user_id}/enable",
status_code=status.HTTP_204_NO_CONTENT,
dependencies=[Depends(get_current_admin)],
)
async def enable_user(user_id: int, db: AsyncSession = Depends(get_db)):
user = await _get_user(user_id, db)
user.is_disabled = False
await db.commit()
@router.delete(
"/users/{user_id}",
status_code=status.HTTP_204_NO_CONTENT,
dependencies=[Depends(get_current_admin)],
)
async def delete_user(user_id: int, db: AsyncSession = Depends(get_db)):
user = await _get_user(user_id, db)
email = user.email
await db.delete(user)
await db.commit()
await notify("Account deleted", f"{email} was deleted.", tags=["warning"])
# ── Notifications ────────────────────────────────────────────────────────────
def _ntfy_settings_out(row: AdminSettings) -> AdminNtfySettingsOut:
return AdminNtfySettingsOut(
ntfy_server_url=row.ntfy_server_url,
ntfy_topic=row.ntfy_topic,
has_token=bool(row.ntfy_token),
)
@router.get("/ntfy-settings", response_model=AdminNtfySettingsOut, dependencies=[Depends(get_current_admin)])
async def get_ntfy_settings(db: AsyncSession = Depends(get_db)):
row = await _get_admin_settings(db)
await db.commit()
return _ntfy_settings_out(row)
@router.put("/ntfy-settings", response_model=AdminNtfySettingsOut, dependencies=[Depends(get_current_admin)])
async def update_ntfy_settings(body: AdminNtfySettingsUpdate, db: AsyncSession = Depends(get_db)):
row = await _get_admin_settings(db)
if body.ntfy_server_url is not None:
row.ntfy_server_url = body.ntfy_server_url.strip() or None
if body.ntfy_topic is not None:
row.ntfy_topic = body.ntfy_topic.strip() or None
if body.ntfy_token is not None:
row.ntfy_token = encrypt(body.ntfy_token) if body.ntfy_token else None
await db.commit()
await db.refresh(row)
return _ntfy_settings_out(row)
@router.post(
"/ntfy-settings/test",
status_code=status.HTTP_204_NO_CONTENT,
dependencies=[Depends(get_current_admin)],
)
async def test_ntfy_settings():
ok = await notify(
"Test notification",
"This is a test notification from the Bourbonacci admin panel.",
tags=["white_check_mark"],
)
if not ok:
raise HTTPException(status_code=502, detail="Failed to send test notification. Check your ntfy settings.")
# ── Reset ────────────────────────────────────────────────────────────────────
async def _safety_backup(db: AsyncSession) -> str:
"""Run a fresh backup before a destructive reset. Refuses to proceed
(raises 502) if the backup itself fails, so a broken backup path can
never leave a reset with no safety net."""
try:
backup = await run_backup(db)
except BackupError as exc:
raise HTTPException(status_code=502, detail=f"Safety backup failed, reset aborted: {exc}")
return backup.filename
@router.post("/reset/entries", response_model=ResetResultOut, dependencies=[Depends(get_current_admin)])
async def reset_entries(db: AsyncSession = Depends(get_db)):
"""Delete every entry for every user. User accounts and settings are untouched."""
backup_filename = await _safety_backup(db)
result = await db.execute(delete(Entry))
await db.commit()
await notify(
"Entries reset",
f"All entries were deleted ({result.rowcount or 0} rows). Safety backup: {backup_filename}",
priority="high",
tags=["rotating_light"],
)
return ResetResultOut(entries_deleted=result.rowcount or 0, backup_filename=backup_filename)