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:
derekcandClaude Opus 5.5 committed 2026-11-23 00:24:19 -08:00
1 parent c54d2b251f
commit 6272322f31
28 files changed
+1523 -461

No files matched your search

+207 -115
View File
@@ -1,149 +1,241 @@
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
import secrets
from datetime import datetime, timedelta, timezone
from app.dependencies import get_db, get_current_admin, bearer_scheme
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.user import AdminUserCreate, AdminPasswordReset, AdminUserResponse, Token
from app.utils.security import hash_password, create_token
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"])
@router.get("/users", response_model=list[AdminUserResponse])
async def list_users(
_: User = Depends(get_current_admin),
db: AsyncSession = Depends(get_db),
):
result = await db.execute(select(User).order_by(User.created_at))
return result.scalars().all()
MAX_FAILED_ADMIN_ATTEMPTS = 5
ADMIN_LOCKOUT_MINUTES = 15
@router.post("/users", response_model=AdminUserResponse, status_code=status.HTTP_201_CREATED)
async def create_user(
body: AdminUserCreate,
_: User = Depends(get_current_admin),
db: AsyncSession = Depends(get_db),
):
result = await db.execute(select(User).where(User.email == body.email))
if result.scalar_one_or_none():
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Email already registered")
def _utcnow() -> datetime:
# MySQL DATETIME columns are naive; store UTC.
return datetime.now(timezone.utc).replace(tzinfo=None)
user = User(
email=body.email,
password_hash=hash_password(body.password),
display_name=body.display_name or body.email.split("@")[0],
is_admin=False,
)
db.add(user)
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 db.refresh(user)
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", status_code=status.HTTP_204_NO_CONTENT)
async def reset_password(
user_id: int,
body: AdminPasswordReset,
_: User = Depends(get_current_admin),
db: AsyncSession = Depends(get_db),
):
result = await db.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
user.password_hash = hash_password(body.new_password)
@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)
async def disable_user(
user_id: int,
current_admin: User = Depends(get_current_admin),
db: AsyncSession = Depends(get_db),
):
if user_id == current_admin.id:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot disable your own account")
result = await db.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
@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} (by admin {current_admin.email})", priority="default")
await notify("User disabled", f"Account disabled: {user.email}")
@router.post("/users/{user_id}/enable", status_code=status.HTTP_204_NO_CONTENT)
async def enable_user(
user_id: int,
_: User = Depends(get_current_admin),
db: AsyncSession = Depends(get_db),
):
result = await db.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
@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)
async def delete_user(
user_id: int,
current_admin: User = Depends(get_current_admin),
db: AsyncSession = Depends(get_db),
):
if user_id == current_admin.id:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot delete your own account")
result = await db.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
@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("User Deleted", f"Account deleted: {user.email} (by admin {current_admin.email})", priority="default")
await notify("Account deleted", f"{email} was deleted.", tags=["warning"])
@router.post("/users/{user_id}/impersonate", response_model=Token)
async def impersonate_user(
user_id: int,
current_admin: User = Depends(get_current_admin),
db: AsyncSession = Depends(get_db),
):
if user_id == current_admin.id:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot impersonate yourself")
# ── Notifications ────────────────────────────────────────────────────────────
result = await db.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
return Token(access_token=create_token(user.id, admin_id=current_admin.id))
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.post("/unimpersonate", response_model=Token)
async def unimpersonate(
credentials=Depends(bearer_scheme),
db: AsyncSession = Depends(get_db),
):
from app.utils.security import decode_token_full
@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)
token = credentials.credentials
payload = decode_token_full(token)
admin_id = payload.get("admin_id") if payload else None
if not admin_id:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Not an impersonation token")
result = await db.execute(select(User).where(User.id == admin_id))
admin = result.scalar_one_or_none()
if not admin or not admin.is_admin or admin.is_disabled:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin not found")
@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)
return Token(access_token=create_token(admin.id))
@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)
+1 -3
View File
@@ -37,7 +37,7 @@ async def register(request: Request, body: UserCreate, db: AsyncSession = Depend
await db.refresh(user)
logger.info("New user registered: %s", body.email)
await notify("New Registration", f"User registered: {body.email}", priority="default")
await notify("New registration", f"User registered: {body.email}", tags=["bust_in_silhouette"])
return Token(access_token=create_token(user.id))
@@ -56,6 +56,4 @@ async def login(request: Request, body: LoginRequest, db: AsyncSession = Depends
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Account disabled")
logger.info("Login: %s (id=%s)", body.email, user.id)
if user.is_admin:
await notify("Admin Login", f"Admin login: {body.email}", priority="high")
return Token(access_token=create_token(user.id))
+104
View File
@@ -0,0 +1,104 @@
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")