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
+207
-115
@@ -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)
|
||||
Reference in new issue
Block a user