Files
bourbonacci/backend/app/routers/backups.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

105 lines
3.6 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app import scheduler
from app.dependencies import get_current_admin, get_db
from app.models.admin_settings import AdminSettings
from app.schemas.admin import (
BackupFileOut,
BackupSettingsOut,
BackupSettingsUpdate,
RestoreRequest,
RestoreResult,
)
from app.services.backup import (
BackupError,
delete_backup,
list_backups,
normalize_backup_location,
restore_backup,
run_backup,
)
from app.utils.notify import notify
router = APIRouter(
prefix="/api/admin/backups", tags=["backups"], dependencies=[Depends(get_current_admin)]
)
async def _get_settings_row(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.commit()
await db.refresh(row)
return row
@router.get("/settings", response_model=BackupSettingsOut)
async def get_backup_settings(db: AsyncSession = Depends(get_db)):
return await _get_settings_row(db)
@router.put("/settings", response_model=BackupSettingsOut)
async def update_backup_settings(body: BackupSettingsUpdate, db: AsyncSession = Depends(get_db)):
try:
location = normalize_backup_location(body.backup_location)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
row = await _get_settings_row(db)
row.backup_enabled = body.backup_enabled
row.backup_frequency = body.backup_frequency
row.backup_hour = body.backup_hour
row.backup_weekday = body.backup_weekday
row.backup_retention = body.backup_retention
row.backup_location = location
await db.commit()
await db.refresh(row)
scheduler.reschedule(row.backup_enabled, row.backup_frequency, row.backup_hour, row.backup_weekday)
return row
@router.get("", response_model=list[BackupFileOut])
async def list_backup_files(db: AsyncSession = Depends(get_db)):
row = await _get_settings_row(db)
return list_backups(row.backup_location)
@router.post("/run", response_model=BackupFileOut, status_code=status.HTTP_201_CREATED)
async def run_backup_now(db: AsyncSession = Depends(get_db)):
try:
return await run_backup(db)
except BackupError as exc:
raise HTTPException(status_code=502, detail=f"Backup failed: {exc}")
@router.post("/{filename}/restore", response_model=RestoreResult)
async def restore_backup_file(filename: str, body: RestoreRequest, db: AsyncSession = Depends(get_db)):
try:
await restore_backup(filename, body.scope, db)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid backup filename")
except FileNotFoundError:
raise HTTPException(status_code=404, detail="Backup file not found")
except BackupError as exc:
raise HTTPException(status_code=502, detail=f"Restore failed: {exc}")
await notify(
"Backup restored",
f"Restored '{filename}' (scope: {body.scope}).",
priority="high",
tags=["rotating_light"],
)
return RestoreResult(scope=body.scope, filename=filename)
@router.delete("/{filename}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_backup_file(filename: str, db: AsyncSession = Depends(get_db)):
row = await _get_settings_row(db)
try:
delete_backup(filename, row.backup_location)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid backup filename")