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

BIN
View File
Binary file not shown.
+9 -6
View File
@@ -9,13 +9,16 @@ DATABASE_URL=mysql+aiomysql://bourbonacci:changeme_db@db:3306/bourbonacci
SECRET_KEY=changeme_generate_a_long_random_string_here SECRET_KEY=changeme_generate_a_long_random_string_here
ACCESS_TOKEN_EXPIRE_MINUTES=480 ACCESS_TOKEN_EXPIRE_MINUTES=480
# Admin account (seeded on every container start) # Out-of-band admin login (used from the normal sign-in form). Not a real user
ADMIN_USERNAME=[email protected] # account -- must not match any user's email. Leave both blank to disable the
ADMIN_PASSWORD=changeme_admin # admin panel entirely. Ntfy notifications are configured in the admin panel.
ADMIN_USERNAME=admin
ADMIN_PASSWORD=set-a-strong-admin-password
# CORS: comma-separated list of allowed origins # CORS: comma-separated list of allowed origins
ALLOWED_ORIGINS=https://yourdomain.com ALLOWED_ORIGINS=https://yourdomain.com
# Ntfy push notifications (optional — leave blank to disable) # NFS share docker-compose mounts into the backend container at /backups
NTFY_URL=https://ntfy.example.com/your-topic # (admin panel > Backups), so backups live off-host. Must be writable by uid 1000.
NTFY_TOKEN= BACKUP_NFS_HOST=172.16.21.51
BACKUP_NFS_PATH=/mnt/pool1/bourbonacci-backups
+9 -1
View File
@@ -2,12 +2,20 @@ FROM python:3.12-slim
WORKDIR /app WORKDIR /app
# mariadb-client provides mariadb-dump / mariadb, used by app/services/backup.py
# for the admin panel's backups and restores (works against the MySQL 8 server).
RUN apt-get update && apt-get install -y --no-install-recommends mariadb-client \
&& rm -rf /var/lib/apt/lists/*
COPY requirements.txt . COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt RUN pip install --no-cache-dir -r requirements.txt
COPY app/ ./app/ COPY app/ ./app/
RUN useradd -r -s /bin/false appuser # uid 1000 so the NFS backup share (writable by uid 1000) mounted at /backups works.
RUN useradd -r -u 1000 -s /bin/false appuser \
&& mkdir -p /backups \
&& chown appuser:appuser /backups
USER appuser USER appuser
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
+3 -5
View File
@@ -1,4 +1,3 @@
from typing import Optional
from pydantic_settings import BaseSettings from pydantic_settings import BaseSettings
@@ -7,11 +6,10 @@ class Settings(BaseSettings):
secret_key: str secret_key: str
access_token_expire_minutes: int = 480 access_token_expire_minutes: int = 480
algorithm: str = "HS256" algorithm: str = "HS256"
admin_username: str # Out-of-band admin login (not a DB user). Both must be set to enable it.
admin_password: str admin_username: str = ""
admin_password: str = ""
allowed_origins: str = "http://localhost" allowed_origins: str = "http://localhost"
ntfy_url: Optional[str] = None
ntfy_token: Optional[str] = None
class Config: class Config:
env_file = ".env" env_file = ".env"
+1 -1
View File
@@ -14,7 +14,7 @@ class Base(DeclarativeBase):
async def init_db() -> None: async def init_db() -> None:
# Import models so their tables are registered on Base.metadata before create_all # Import models so their tables are registered on Base.metadata before create_all
from app.models import user, entry # noqa: F401 from app.models import user, entry, admin_settings # noqa: F401
async with engine.begin() as conn: async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all) await conn.run_sync(Base.metadata.create_all)
+5 -5
View File
@@ -6,7 +6,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select from sqlalchemy import select
from app.database import AsyncSessionLocal from app.database import AsyncSessionLocal
from app.utils.security import decode_token from app.utils.security import decode_token, is_admin_token
bearer_scheme = HTTPBearer() bearer_scheme = HTTPBearer()
@@ -37,7 +37,7 @@ async def get_current_user(
return user return user
async def get_current_admin(current_user=Depends(get_current_user)): async def get_current_admin(credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme)) -> None:
if not current_user.is_admin: # Out-of-band admin: authenticated by an admin-only JWT, not a DB user.
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin access required") if not is_admin_token(credentials.credentials):
return current_user raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Admin access required")
+6 -23
View File
@@ -3,14 +3,14 @@ from contextlib import asynccontextmanager
from fastapi import FastAPI from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy import select
from slowapi import _rate_limit_exceeded_handler from slowapi import _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded from slowapi.errors import RateLimitExceeded
from app.config import settings from app.config import settings
from app.database import init_db, AsyncSessionLocal from app import scheduler
from app.database import init_db
from app.limiter import limiter from app.limiter import limiter
from app.routers import auth, users, entries, public, admin from app.routers import auth, users, entries, public, admin, backups
logging.basicConfig( logging.basicConfig(
level=logging.INFO, level=logging.INFO,
@@ -19,31 +19,13 @@ logging.basicConfig(
logger = logging.getLogger("bourbonacci") logger = logging.getLogger("bourbonacci")
async def _seed_admin() -> None:
from app.models.user import User
from app.utils.security import hash_password
async with AsyncSessionLocal() as db:
result = await db.execute(select(User).where(User.email == settings.admin_username))
user = result.scalar_one_or_none()
if user is None:
db.add(User(
email=settings.admin_username,
password_hash=hash_password(settings.admin_password),
display_name="Admin",
is_admin=True,
))
elif not user.is_admin:
user.is_admin = True
await db.commit()
@asynccontextmanager @asynccontextmanager
async def lifespan(app: FastAPI): async def lifespan(app: FastAPI):
await init_db() await init_db()
await _seed_admin() await scheduler.start()
logger.info("Bourbonacci started") logger.info("Bourbonacci started")
yield yield
scheduler.shutdown()
logger.info("Bourbonacci shutting down") logger.info("Bourbonacci shutting down")
@@ -64,6 +46,7 @@ app.include_router(users.router)
app.include_router(entries.router) app.include_router(entries.router)
app.include_router(public.router) app.include_router(public.router)
app.include_router(admin.router) app.include_router(admin.router)
app.include_router(backups.router)
@app.get("/health") @app.get("/health")
+34
View File
@@ -0,0 +1,34 @@
from datetime import datetime
from typing import Optional
from sqlalchemy import Boolean, DateTime, Integer, String
from sqlalchemy.orm import Mapped, mapped_column
from app.database import Base
class AdminSettings(Base):
"""Single-row table (id=1) holding admin-only config that's edited live from the admin panel."""
__tablename__ = "admin_settings"
id: Mapped[int] = mapped_column(primary_key=True)
ntfy_server_url: Mapped[Optional[str]] = mapped_column(String(255))
ntfy_topic: Mapped[Optional[str]] = mapped_column(String(255))
ntfy_token: Mapped[Optional[str]] = mapped_column(String(500))
# Scheduled backups (see routers/backups.py, services/backup.py).
backup_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
backup_frequency: Mapped[str] = mapped_column(String(10), nullable=False, default="daily")
backup_hour: Mapped[int] = mapped_column(Integer, nullable=False, default=3) # 0-23, UTC
backup_weekday: Mapped[int] = mapped_column(Integer, nullable=False, default=0) # 0=Mon, used if weekly
backup_retention: Mapped[int] = mapped_column(Integer, nullable=False, default=14)
# Optional subfolder under the mounted /backups directory.
backup_location: Mapped[Optional[str]] = mapped_column(String(255))
last_backup_at: Mapped[Optional[datetime]] = mapped_column(DateTime) # UTC
last_backup_status: Mapped[Optional[str]] = mapped_column(String(20)) # "success" | "error"
last_backup_error: Mapped[Optional[str]] = mapped_column(String(2000))
# Brute-force protection for the out-of-band admin login.
admin_failed_attempts: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
admin_locked_until: Mapped[Optional[datetime]] = mapped_column(DateTime) # UTC
+207 -115
View File
@@ -1,149 +1,241 @@
from fastapi import APIRouter, Depends, HTTPException, status import secrets
from sqlalchemy.ext.asyncio import AsyncSession from datetime import datetime, timedelta, timezone
from sqlalchemy import select
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.models.user import User
from app.schemas.user import AdminUserCreate, AdminPasswordReset, AdminUserResponse, Token from app.schemas.admin import (
from app.utils.security import hash_password, create_token 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.notify import notify
from app.utils.security import create_admin_token, hash_password
router = APIRouter(prefix="/api/admin", tags=["admin"]) router = APIRouter(prefix="/api/admin", tags=["admin"])
MAX_FAILED_ADMIN_ATTEMPTS = 5
@router.get("/users", response_model=list[AdminUserResponse]) ADMIN_LOCKOUT_MINUTES = 15
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()
@router.post("/users", response_model=AdminUserResponse, status_code=status.HTTP_201_CREATED) def _utcnow() -> datetime:
async def create_user( # MySQL DATETIME columns are naive; store UTC.
body: AdminUserCreate, return datetime.now(timezone.utc).replace(tzinfo=None)
_: 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")
user = User(
email=body.email, async def _get_admin_settings(db: AsyncSession) -> AdminSettings:
password_hash=hash_password(body.password), row = (await db.execute(select(AdminSettings).where(AdminSettings.id == 1))).scalar_one_or_none()
display_name=body.display_name or body.email.split("@")[0], if not row:
is_admin=False, row = AdminSettings(id=1)
) db.add(row)
db.add(user) 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.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 return user
@router.post("/users/{user_id}/reset-password", status_code=status.HTTP_204_NO_CONTENT) @router.post(
async def reset_password( "/users/{user_id}/reset-password",
user_id: int, response_model=ResetPasswordOut,
body: AdminPasswordReset, dependencies=[Depends(get_current_admin)],
_: User = Depends(get_current_admin), )
db: AsyncSession = Depends(get_db), async def reset_password(user_id: int, db: AsyncSession = Depends(get_db)):
): user = await _get_user(user_id, db)
result = await db.execute(select(User).where(User.id == user_id)) temp_password = secrets.token_urlsafe(9)
user = result.scalar_one_or_none() user.password_hash = hash_password(temp_password)
if not user:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
user.password_hash = hash_password(body.new_password)
await db.commit() 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) @router.post(
async def disable_user( "/users/{user_id}/disable",
user_id: int, status_code=status.HTTP_204_NO_CONTENT,
current_admin: User = Depends(get_current_admin), dependencies=[Depends(get_current_admin)],
db: AsyncSession = Depends(get_db), )
): async def disable_user(user_id: int, db: AsyncSession = Depends(get_db)):
if user_id == current_admin.id: user = await _get_user(user_id, db)
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")
user.is_disabled = True user.is_disabled = True
await db.commit() 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) @router.post(
async def enable_user( "/users/{user_id}/enable",
user_id: int, status_code=status.HTTP_204_NO_CONTENT,
_: User = Depends(get_current_admin), dependencies=[Depends(get_current_admin)],
db: AsyncSession = Depends(get_db), )
): async def enable_user(user_id: int, db: AsyncSession = Depends(get_db)):
result = await db.execute(select(User).where(User.id == user_id)) user = await _get_user(user_id, db)
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
user.is_disabled = False user.is_disabled = False
await db.commit() await db.commit()
@router.delete("/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT) @router.delete(
async def delete_user( "/users/{user_id}",
user_id: int, status_code=status.HTTP_204_NO_CONTENT,
current_admin: User = Depends(get_current_admin), dependencies=[Depends(get_current_admin)],
db: AsyncSession = Depends(get_db), )
): async def delete_user(user_id: int, db: AsyncSession = Depends(get_db)):
if user_id == current_admin.id: user = await _get_user(user_id, db)
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot delete your own account") email = user.email
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")
await db.delete(user) await db.delete(user)
await db.commit() 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) # ── Notifications ────────────────────────────────────────────────────────────
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")
result = await db.execute(select(User).where(User.id == user_id)) def _ntfy_settings_out(row: AdminSettings) -> AdminNtfySettingsOut:
user = result.scalar_one_or_none() return AdminNtfySettingsOut(
if not user: ntfy_server_url=row.ntfy_server_url,
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found") ntfy_topic=row.ntfy_topic,
has_token=bool(row.ntfy_token),
return Token(access_token=create_token(user.id, admin_id=current_admin.id)) )
@router.post("/unimpersonate", response_model=Token) @router.get("/ntfy-settings", response_model=AdminNtfySettingsOut, dependencies=[Depends(get_current_admin)])
async def unimpersonate( async def get_ntfy_settings(db: AsyncSession = Depends(get_db)):
credentials=Depends(bearer_scheme), row = await _get_admin_settings(db)
db: AsyncSession = Depends(get_db), await db.commit()
): return _ntfy_settings_out(row)
from app.utils.security import decode_token_full
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)) @router.put("/ntfy-settings", response_model=AdminNtfySettingsOut, dependencies=[Depends(get_current_admin)])
admin = result.scalar_one_or_none() async def update_ntfy_settings(body: AdminNtfySettingsUpdate, db: AsyncSession = Depends(get_db)):
if not admin or not admin.is_admin or admin.is_disabled: row = await _get_admin_settings(db)
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin not found") 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) await db.refresh(user)
logger.info("New user registered: %s", body.email) 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)) 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") raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Account disabled")
logger.info("Login: %s (id=%s)", body.email, user.id) 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)) 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")
+48
View File
@@ -0,0 +1,48 @@
import logging
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from sqlalchemy import select
from app.database import AsyncSessionLocal
from app.models.admin_settings import AdminSettings
from app.services.backup import run_backup
logger = logging.getLogger("bourbonacci.scheduler")
_JOB_ID = "scheduled_backup"
_scheduler = AsyncIOScheduler(timezone="UTC")
async def _run_scheduled_backup() -> None:
async with AsyncSessionLocal() as db:
try:
await run_backup(db)
except Exception:
logger.exception("Scheduled backup failed")
def reschedule(enabled: bool, frequency: str, hour: int, weekday: int) -> None:
if _scheduler.get_job(_JOB_ID):
_scheduler.remove_job(_JOB_ID)
if not enabled:
return
trigger = CronTrigger(
hour=hour,
minute=0,
day_of_week=weekday if frequency == "weekly" else "*",
timezone="UTC",
)
_scheduler.add_job(_run_scheduled_backup, trigger, id=_JOB_ID, replace_existing=True)
async def start() -> None:
async with AsyncSessionLocal() as db:
row = (await db.execute(select(AdminSettings).where(AdminSettings.id == 1))).scalar_one_or_none()
if row:
reschedule(row.backup_enabled, row.backup_frequency, row.backup_hour, row.backup_weekday)
_scheduler.start()
def shutdown() -> None:
_scheduler.shutdown(wait=False)
+96
View File
@@ -0,0 +1,96 @@
from datetime import datetime, timezone
from typing import Literal, Optional
from pydantic import BaseModel, Field, field_validator
def _as_utc(v: Optional[datetime]) -> Optional[datetime]:
# MySQL DATETIME columns come back naive; they're stored as UTC.
if v is not None and v.tzinfo is None:
return v.replace(tzinfo=timezone.utc)
return v
class AdminLogin(BaseModel):
username: str
password: str
class AdminTokenOut(BaseModel):
access_token: str
token_type: str = "bearer"
class AdminUserOut(BaseModel):
id: int
email: str
display_name: Optional[str]
created_at: datetime
is_disabled: bool
entry_count: int
class ResetPasswordOut(BaseModel):
temp_password: str
class ResetResultOut(BaseModel):
entries_deleted: int = 0
# Filename of the safety backup taken automatically right before the reset.
backup_filename: Optional[str] = None
class AdminNtfySettingsOut(BaseModel):
ntfy_server_url: Optional[str]
ntfy_topic: Optional[str]
has_token: bool
class AdminNtfySettingsUpdate(BaseModel):
ntfy_server_url: Optional[str] = None
ntfy_topic: Optional[str] = None
ntfy_token: Optional[str] = None
BackupScope = Literal["entries", "all"]
BackupFrequency = Literal["daily", "weekly"]
class BackupSettingsOut(BaseModel):
backup_enabled: bool
backup_frequency: BackupFrequency
backup_hour: int
backup_weekday: int
backup_retention: int
backup_location: Optional[str] = None
last_backup_at: Optional[datetime] = None
last_backup_status: Optional[str] = None
last_backup_error: Optional[str] = None
model_config = {"from_attributes": True}
_utc = field_validator("last_backup_at")(_as_utc)
class BackupSettingsUpdate(BaseModel):
backup_enabled: bool
backup_frequency: BackupFrequency = "daily"
backup_hour: int = Field(default=3, ge=0, le=23)
backup_weekday: int = Field(default=0, ge=0, le=6)
backup_retention: int = Field(default=14, ge=1, le=365)
backup_location: Optional[str] = Field(default=None, max_length=255)
class BackupFileOut(BaseModel):
filename: str
size_bytes: int
created_at: datetime
class RestoreRequest(BaseModel):
scope: BackupScope
class RestoreResult(BaseModel):
scope: BackupScope
filename: str
-23
View File
@@ -26,7 +26,6 @@ class UserResponse(BaseModel):
display_name: Optional[str] display_name: Optional[str]
timezone: str timezone: str
bottle_size: Optional[float] bottle_size: Optional[float]
is_admin: bool
created_at: datetime created_at: datetime
model_config = {"from_attributes": True} model_config = {"from_attributes": True}
@@ -40,25 +39,3 @@ class Token(BaseModel):
class LoginRequest(BaseModel): class LoginRequest(BaseModel):
email: EmailStr email: EmailStr
password: str password: str
class AdminUserCreate(BaseModel):
email: EmailStr
password: str
display_name: Optional[str] = None
class AdminPasswordReset(BaseModel):
new_password: str
class AdminUserResponse(BaseModel):
id: int
email: str
display_name: Optional[str]
timezone: str
is_admin: bool
is_disabled: bool
created_at: datetime
model_config = {"from_attributes": True}
View File
Whitespace-only changes.
+229
View File
@@ -0,0 +1,229 @@
import asyncio
import gzip
import logging
import os
import re
import secrets
from datetime import datetime, timezone
from pathlib import Path
from typing import Literal
from sqlalchemy import select
from sqlalchemy.engine import make_url
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database import engine
from app.models.admin_settings import AdminSettings
from app.schemas.admin import BackupFileOut
logger = logging.getLogger("bourbonacci.backup")
BACKUP_ROOT = Path("/backups")
_FILENAME_PREFIX = "bourbonacci_"
_FILENAME_SUFFIX = ".sql.gz"
_TABLE_MARKER = re.compile(rb"^-- Table structure for table `([^`]+)`", re.MULTILINE)
# First statement of the trailer mysqldump/mariadb-dump writes after the last table.
_TRAILER_MARKER = re.compile(rb"^/\*!40103 SET TIME_ZONE=@OLD_TIME_ZONE \*/;", re.MULTILINE)
class BackupError(Exception):
"""A mariadb-dump/mariadb subprocess exited non-zero."""
def _utcnow() -> datetime:
# MySQL DATETIME columns are naive; store UTC.
return datetime.now(timezone.utc).replace(tzinfo=None)
def _conn_args() -> tuple[list[str], dict[str, str]]:
"""Connection flags for the MariaDB CLI tools, derived from DATABASE_URL.
The password goes in MYSQL_PWD so it never shows up in the process list."""
url = make_url(settings.database_url)
args = [
"-h", url.host or "localhost",
"-P", str(url.port or 3306),
"-u", url.username or "",
# MySQL 8.4 serves TLS with an auto-generated self-signed cert.
"--skip-ssl-verify-server-cert",
]
env = {**os.environ, "MYSQL_PWD": url.password or ""}
return args, env
def _db_name() -> str:
return make_url(settings.database_url).database or ""
async def _get_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
_LOCATION_RE = re.compile(r"^[A-Za-z0-9_-]+(/[A-Za-z0-9_-]+)*$")
def normalize_backup_location(location: str | None) -> str | None:
"""Validate the admin's optional backup subfolder: plain folder names
(letters, digits, - and _) nested with "/", so it can't point outside
BACKUP_ROOT. Raises ValueError otherwise."""
location = (location or "").strip().strip("/")
if not location:
return None
if not _LOCATION_RE.match(location):
raise ValueError("Subfolder may only contain letters, numbers, - and _, separated by /.")
return location
def backup_dir(location: str | None = None) -> Path:
d = BACKUP_ROOT / location.strip("/") if location else BACKUP_ROOT
# Belt and braces alongside normalize_backup_location: never create or
# use a directory outside BACKUP_ROOT, whatever is stored in the row.
if not d.resolve().is_relative_to(BACKUP_ROOT.resolve()):
raise ValueError("Backup location must be inside the backup directory")
d.mkdir(parents=True, exist_ok=True)
return d
def _resolve_backup_file(filename: str, location: str | None) -> Path:
"""Resolve a filename against the backup directory, rejecting anything
that escapes it (path traversal via `..`, absolute paths, etc)."""
base = backup_dir(location).resolve()
candidate = (base / filename).resolve()
if not candidate.is_relative_to(base) or candidate.parent != base:
raise ValueError("Invalid backup filename")
return candidate
def list_backups(location: str | None = None) -> list[BackupFileOut]:
d = backup_dir(location)
files = [
BackupFileOut(
filename=f.name,
size_bytes=f.stat().st_size,
created_at=datetime.fromtimestamp(f.stat().st_mtime, tz=timezone.utc),
)
for f in d.iterdir()
if f.is_file() and f.name.startswith(_FILENAME_PREFIX) and f.name.endswith(_FILENAME_SUFFIX)
]
files.sort(key=lambda b: b.created_at, reverse=True)
return files
def prune_backups(retention: int, location: str | None = None) -> int:
files = list_backups(location)
to_delete = files[retention:]
for f in to_delete:
(backup_dir(location) / f.filename).unlink(missing_ok=True)
return len(to_delete)
async def _dump_to(path: Path) -> None:
conn, env = _conn_args()
proc = await asyncio.create_subprocess_exec(
"mariadb-dump", *conn,
"--single-transaction", "--no-tablespaces", "--skip-lock-tables",
_db_name(),
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=env,
)
stderr_task = asyncio.create_task(proc.stderr.read())
with gzip.open(path, "wb") as out:
while chunk := await proc.stdout.read(65536):
out.write(chunk)
stderr = await stderr_task
await proc.wait()
if proc.returncode != 0:
raise BackupError(stderr.decode(errors="replace").strip() or f"mariadb-dump exited {proc.returncode}")
async def _load_sql(sql: bytes) -> None:
conn, env = _conn_args()
proc = await asyncio.create_subprocess_exec(
"mariadb", *conn, _db_name(),
stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=env,
)
_, stderr = await proc.communicate(input=sql)
if proc.returncode != 0:
raise BackupError(stderr.decode(errors="replace").strip() or f"mariadb exited {proc.returncode}")
def _extract_table(sql: bytes, table: str) -> bytes:
"""Return the dump's header + the given table's DROP/CREATE/INSERT section + trailer,
so just that one table can be reloaded from a full-database dump."""
markers = list(_TABLE_MARKER.finditer(sql))
trailer = _TRAILER_MARKER.search(sql)
if not markers or not trailer:
raise BackupError("Backup file is not in the expected mysqldump format")
header = sql[: markers[0].start()]
for i, m in enumerate(markers):
if m.group(1).decode() == table:
end = markers[i + 1].start() if i + 1 < len(markers) else trailer.start()
return header + sql[m.start(): end] + sql[trailer.start():]
raise BackupError(f"Backup file has no `{table}` table")
async def run_backup(db: AsyncSession) -> BackupFileOut:
row = await _get_settings(db)
d = backup_dir(row.backup_location)
# A short random suffix guards against two backups landing in the same
# second (e.g. rapid "Backup now" clicks), which would otherwise silently
# overwrite one another.
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
path = d / f"{_FILENAME_PREFIX}{stamp}_{secrets.token_hex(3)}{_FILENAME_SUFFIX}"
try:
await _dump_to(path)
except BackupError as exc:
path.unlink(missing_ok=True)
row.last_backup_at = _utcnow()
row.last_backup_status = "error"
row.last_backup_error = str(exc)[:2000]
await db.commit()
logger.error("Backup failed: %s", exc)
raise
# Full user data in plaintext -- keep it readable only by the app user.
path.chmod(0o600)
prune_backups(row.backup_retention, row.backup_location)
row.last_backup_at = _utcnow()
row.last_backup_status = "success"
row.last_backup_error = None
await db.commit()
stat = path.stat()
return BackupFileOut(
filename=path.name,
size_bytes=stat.st_size,
created_at=datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc),
)
async def restore_backup(filename: str, scope: Literal["entries", "all"], db: AsyncSession) -> None:
row = await _get_settings(db)
path = _resolve_backup_file(filename, row.backup_location)
if not path.is_file():
raise FileNotFoundError(filename)
# Reading admin_settings above left this session in an open transaction
# holding a metadata lock on that table; a full restore DROPs and
# recreates it, which would block on that lock. Close the transaction first.
await db.commit()
sql = await asyncio.to_thread(lambda: gzip.decompress(path.read_bytes()))
if scope == "entries":
sql = _extract_table(sql, "entries")
await _load_sql(sql)
# Tables were dropped and recreated -- discard pooled connections so none
# carries state from before the restore.
await engine.dispose()
def delete_backup(filename: str, location: str | None) -> None:
path = _resolve_backup_file(filename, location)
path.unlink(missing_ok=True)
+21
View File
@@ -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
View File
@@ -1,19 +1,69 @@
import base64
import logging 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") logger = logging.getLogger("bourbonacci.notify")
async def notify(title: str, message: str, priority: str = "default") -> None: def _header_value(value: str) -> str:
if not settings.ntfy_url: # HTTP header values must be ASCII; ntfy decodes RFC 2047 encoded-words,
return # so send non-ASCII titles/tags that way and leave plain ASCII untouched.
headers = {"Title": f"Bourbonacci Admin - {title}", "Priority": priority} if value.isascii():
if settings.ntfy_token: return value
headers["Authorization"] = f"Bearer {settings.ntfy_token}" 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: try:
async with httpx.AsyncClient(timeout=5) as client: token = decrypt(row.ntfy_token) if row.ntfy_token else None
await client.post(settings.ntfy_url, content=message, headers=headers) except InvalidToken:
except Exception as exc: logger.error("Could not decrypt stored admin ntfy token")
logger.warning("Ntfy notification failed: %s", exc) 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
+11 -6
View File
@@ -17,14 +17,18 @@ def verify_password(plain: str, hashed: str) -> bool:
return pwd_context.verify(plain, hashed) 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) expire = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes)
payload: dict = {"sub": str(user_id), "exp": expire} 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) 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]: def decode_token(token: str) -> Optional[int]:
try: try:
payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm]) payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
@@ -36,8 +40,9 @@ def decode_token(token: str) -> Optional[int]:
return None return None
def decode_token_full(token: str) -> Optional[dict]: def is_admin_token(token: str) -> bool:
try: try:
return jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm]) payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
except JWTError: except JWTError:
return None return False
return payload.get("admin") is True
+2
View File
@@ -11,3 +11,5 @@ pytz==2026.6
email-validator==2.4.0 email-validator==2.4.0
slowapi==0.1.10 slowapi==0.1.10
httpx==0.28.1 httpx==0.28.1
cryptography==50.0.2
apscheduler==3.11.3
+12 -2
View File
@@ -21,8 +21,10 @@ services:
- ADMIN_USERNAME=${ADMIN_USERNAME} - ADMIN_USERNAME=${ADMIN_USERNAME}
- ADMIN_PASSWORD=${ADMIN_PASSWORD} - ADMIN_PASSWORD=${ADMIN_PASSWORD}
- ALLOWED_ORIGINS=${ALLOWED_ORIGINS:-http://localhost} - ALLOWED_ORIGINS=${ALLOWED_ORIGINS:-http://localhost}
- NTFY_URL=${NTFY_URL:-} volumes:
- NTFY_TOKEN=${NTFY_TOKEN:-} # Scheduled/manual backups (admin panel > Backups): the NFS-backed `backups`
# volume below, so they live off-host. The share must be writable by uid 1000.
- backups:/backups
depends_on: depends_on:
db: db:
condition: service_healthy condition: service_healthy
@@ -56,3 +58,11 @@ services:
volumes: volumes:
mysql_data: mysql_data:
# Off-host backups on the project's NFS share. Override the server/export
# with BACKUP_NFS_HOST / BACKUP_NFS_PATH in .env.
backups:
driver: local
driver_opts:
type: nfs
o: "addr=${BACKUP_NFS_HOST:-172.16.21.51},nfsvers=4.1,rw,hard,timeo=600,retrans=2"
device: ":${BACKUP_NFS_PATH:-/mnt/pool1/bourbonacci-backups}"
+22 -50
View File
@@ -11,72 +11,44 @@
<nav> <nav>
<div class="nav-left"> <div class="nav-left">
<a href="/index.html" class="nav-brand">🥃 Bourbonacci</a> <span class="nav-brand">🥃 Bourbonacci — Admin</span>
<div class="nav-links" id="nav-links"></div> </div>
<div class="nav-user">
<button onclick="Admin.signOut()" class="btn btn-sm btn-ghost">Sign out</button>
</div> </div>
<div id="nav-user"></div>
</nav> </nav>
<main> <main>
<h1 class="page-title">Admin — User Management</h1> <div class="tabs">
<div class="tab" data-tab="users" onclick="Admin.showTab('users')">Users</div>
<div id="msg"></div> <div class="tab" data-tab="notifications" onclick="Admin.showTab('notifications')">Notifications</div>
<div class="tab" data-tab="backups" onclick="Admin.showTab('backups')">Backups</div>
<div class="section-header"> <div class="tab" data-tab="reset" onclick="Admin.showTab('reset')">Reset</div>
<h2>All Users</h2>
<button class="btn btn-ghost btn-sm" onclick="loadUsers()">Refresh</button>
</div> </div>
<div class="table-wrap"> <div id="tab-content"></div>
<table>
<thead>
<tr>
<th>Display Name</th>
<th>Email</th>
<th>Role</th>
<th>Status</th>
<th>Joined</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="users-body">
<tr class="empty-row"><td colspan="6">Loading…</td></tr>
</tbody>
</table>
</div>
<!-- Reset password modal --> <!-- Delete user confirmation modal -->
<div id="reset-modal" class="modal-overlay" style="display:none">
<div class="modal-box">
<h2>Reset Password</h2>
<p style="margin-bottom:1rem;color:var(--cream-dim)">Setting new password for: <strong id="reset-username"></strong></p>
<div id="reset-msg"></div>
<div class="form-group" style="margin-bottom:1rem">
<label>New Password</label>
<input type="password" id="reset-password" placeholder="Min 8 characters" />
</div>
<div style="display:flex;gap:0.5rem;justify-content:flex-end">
<button class="btn btn-ghost" onclick="hideResetModal()">Cancel</button>
<button class="btn btn-primary" onclick="submitReset()">Set Password</button>
</div>
</div>
</div>
<!-- Delete confirmation modal -->
<div id="delete-modal" class="modal-overlay" style="display:none"> <div id="delete-modal" class="modal-overlay" style="display:none">
<div class="modal-box"> <div class="modal-box">
<h2>Delete User</h2> <h2>Delete User</h2>
<p style="margin-bottom:1.5rem;color:var(--cream-dim)">Delete <strong id="delete-username"></strong>? This will permanently remove their account and all associated data.</p> <p style="margin-bottom:1rem;color:var(--cream-dim)">
This permanently deletes <strong id="delete-email"></strong>'s account and every entry they own.
This cannot be undone. Type the email address to confirm.
</p>
<div id="delete-msg"></div>
<div class="form-group">
<input type="text" id="delete-confirm" autocomplete="off" oninput="Admin.onDeleteConfirmInput()" />
</div>
<div style="display:flex;gap:0.5rem;justify-content:flex-end"> <div style="display:flex;gap:0.5rem;justify-content:flex-end">
<button class="btn btn-ghost" onclick="hideDeleteModal()">Cancel</button> <button class="btn btn-ghost" onclick="Admin.hideDeleteModal()">Cancel</button>
<button class="btn btn-danger" onclick="submitDelete()">Delete</button> <button class="btn btn-danger" id="delete-submit" disabled onclick="Admin.submitDelete()">Delete permanently</button>
</div> </div>
</div> </div>
</div> </div>
</main> </main>
<script src="/js/api.js"></script> <script src="/js/api.js"></script>
<script src="/js/auth.js"></script> <script src="/js/admin.js?v=2"></script>
<script src="/js/admin.js"></script>
</body> </body>
</html> </html>
+19 -16
View File
@@ -81,20 +81,6 @@ nav {
white-space: nowrap; white-space: nowrap;
} }
.nav-impersonating {
color: var(--amber-light);
font-size: 0.85rem;
white-space: nowrap;
}
.btn-amber {
background: var(--amber);
color: #0d0800;
border: none;
}
.btn-amber:hover { background: var(--amber-light); }
/* ---- Modal ---- */ /* ---- Modal ---- */
.modal-overlay { .modal-overlay {
position: fixed; position: fixed;
@@ -140,8 +126,6 @@ nav {
} }
/* ---- Admin badges ---- */ /* ---- Admin badges ---- */
.badge-admin { background: rgba(200,134,10,.2); color: var(--amber-light); border: 1px solid var(--amber-dim); }
.badge-user { background: rgba(245,230,200,.1); color: var(--cream-dim); border: 1px solid var(--border); }
.badge-active { background: rgba(39,174,96,.15); color: #5dd490; border: 1px solid #1e6b3d; } .badge-active { background: rgba(39,174,96,.15); color: #5dd490; border: 1px solid #1e6b3d; }
.badge-disabled { background: rgba(192,57,43,.2); color: #e07060; border: 1px solid var(--danger-dim); } .badge-disabled { background: rgba(192,57,43,.2); color: #e07060; border: 1px solid var(--danger-dim); }
@@ -475,6 +459,25 @@ tbody td {
.tab.active, .tab:hover { color: var(--amber-light); } .tab.active, .tab:hover { color: var(--amber-light); }
.tab.active { border-bottom-color: var(--amber); } .tab.active { border-bottom-color: var(--amber); }
/* ---- Admin panel ---- */
.admin-card { margin-bottom: 1.5rem; }
.card + .admin-card { margin-top: 0; }
.admin-muted { color: var(--cream-dim); font-size: .85rem; margin-bottom: 1rem; }
.admin-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 0 1rem; }
.admin-check { display: flex; align-items: center; gap: .5rem; color: var(--cream); margin-bottom: 1rem; cursor: pointer; }
.admin-check input { width: auto; }
.admin-confirm { display: flex; gap: .5rem; align-items: center; }
.admin-confirm input { max-width: 220px; padding: .4rem .7rem; font-size: .85rem; }
.admin-file { padding: 1rem; margin-bottom: .75rem; }
.admin-file .admin-muted { margin-bottom: 0; }
.admin-file-head { display: flex; justify-content: space-between; align-items: center; gap: 1rem; flex-wrap: wrap; }
.admin-restore { display: flex; gap: 1.5rem; flex-wrap: wrap; margin-top: .75rem; }
.admin-restore label, .admin-card label code { font-size: .8rem; }
.temp-pw { display: flex; gap: .75rem; align-items: center; background: rgba(200,134,10,.12); border: 1px solid var(--amber-dim); border-radius: var(--radius); padding: .5rem .75rem; font-size: .85rem; color: var(--amber-light); }
.temp-pw code { font-size: .95rem; color: var(--cream); }
.text-success { color: #5dd490; }
.text-danger { color: #e07060; }
/* ---- Custom scrollbar ---- */ /* ---- Custom scrollbar ---- */
::-webkit-scrollbar { width: 8px; } ::-webkit-scrollbar { width: 8px; }
::-webkit-scrollbar-track { background: var(--bg-card); } ::-webkit-scrollbar-track { background: var(--bg-card); }
+573 -143
View File
@@ -1,164 +1,594 @@
// admin.js — admin user management page // admin.js — out-of-band admin panel (Users / Notifications / Backups / Reset).
// Uses its own admin token (bb_admin_token), separate from the normal user token.
let resetTargetId = null; const Admin = (() => {
let deleteTargetId = null; const TOKEN_KEY = 'bb_admin_token';
let currentAdminId = null; const TABS = ['users', 'notifications', 'backups', 'reset'];
const WEEKDAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
document.addEventListener('DOMContentLoaded', async () => { // ── API ────────────────────────────────────────────────────────────────────
if (!Auth.requireAuth()) return;
await Auth.renderNav();
const user = Auth.getUser(); function signOut() {
if (!user || !user.is_admin) { localStorage.removeItem(TOKEN_KEY);
window.location.href = '/dashboard.html'; window.location.href = '/login.html';
return;
}
currentAdminId = user.id;
await loadUsers();
});
async function loadUsers() {
try {
const users = await API.admin.listUsers();
renderUsers(users);
} catch (err) {
showMsg(err.message, 'error');
}
}
function renderUsers(users) {
const tbody = document.getElementById('users-body');
if (!users.length) {
tbody.innerHTML = '<tr class="empty-row"><td colspan="6">No users found.</td></tr>';
return;
} }
tbody.innerHTML = users.map(u => { async function request(method, path, body) {
const isSelf = u.id === currentAdminId; const headers = { 'Content-Type': 'application/json' };
const name = escHtml(u.display_name || u.email); const tok = localStorage.getItem(TOKEN_KEY);
const roleLabel = u.is_admin if (tok) headers['Authorization'] = `Bearer ${tok}`;
? '<span class="badge badge-admin">Admin</span>'
: '<span class="badge badge-user">User</span>';
const statusLabel = u.is_disabled
? '<span class="badge badge-disabled">Disabled</span>'
: '<span class="badge badge-active">Active</span>';
const joined = new Date(u.created_at).toLocaleDateString();
const toggleBtn = u.is_disabled const res = await fetch('/api/admin' + path, {
? `<button class="btn btn-sm btn-primary" onclick="toggleUser(${u.id}, false)">Enable</button>` method,
: `<button class="btn btn-sm btn-ghost" onclick="toggleUser(${u.id}, true)"${isSelf ? ' disabled title="Cannot disable yourself"' : ''}>Disable</button>`; headers,
body: body !== undefined ? JSON.stringify(body) : undefined,
});
const impersonateBtn = !isSelf if (res.status === 401 || res.status === 403) {
? `<button class="btn btn-sm btn-ghost" onclick="impersonateUser(${u.id})">Login As</button>` signOut();
: ''; throw new Error('Signed out');
}
if (res.status === 204) return null;
const deleteBtn = !isSelf const data = await res.json().catch(() => null);
? `<button class="btn btn-sm btn-danger" onclick="showDeleteModal(${u.id}, '${name}')">Delete</button>` if (!res.ok) {
: ''; const msg = data?.detail || `HTTP ${res.status}`;
throw new Error(Array.isArray(msg) ? msg.map(e => e.msg).join(', ') : msg);
return `<tr> }
<td><strong>${name}</strong></td> return data;
<td>${escHtml(u.email)}</td>
<td>${roleLabel}</td>
<td>${statusLabel}</td>
<td>${joined}</td>
<td style="display:flex;gap:0.35rem;flex-wrap:wrap">
<button class="btn btn-sm btn-ghost" onclick="showResetModal(${u.id}, '${name}')">Reset PW</button>
${toggleBtn}
${impersonateBtn}
${deleteBtn}
</td>
</tr>`;
}).join('');
}
function showResetModal(id, name) {
resetTargetId = id;
document.getElementById('reset-username').textContent = name;
document.getElementById('reset-password').value = '';
document.getElementById('reset-msg').innerHTML = '';
document.getElementById('reset-modal').style.display = 'flex';
document.getElementById('reset-password').focus();
}
function hideResetModal() {
document.getElementById('reset-modal').style.display = 'none';
resetTargetId = null;
}
async function submitReset() {
const password = document.getElementById('reset-password').value;
const msgEl = document.getElementById('reset-msg');
if (password.length < 8) {
msgEl.innerHTML = '<div class="alert alert-error">Password must be at least 8 characters.</div>';
return;
} }
try { const api = {
await API.admin.resetPassword(resetTargetId, { new_password: password }); listUsers: () => request('GET', '/users'),
msgEl.innerHTML = '<div class="alert alert-success">Password reset successfully.</div>'; resetPassword: (id) => request('POST', `/users/${id}/reset-password`),
setTimeout(hideResetModal, 1200); disableUser: (id) => request('POST', `/users/${id}/disable`),
} catch (err) { enableUser: (id) => request('POST', `/users/${id}/enable`),
msgEl.innerHTML = `<div class="alert alert-error">${escHtml(err.message)}</div>`; deleteUser: (id) => request('DELETE', `/users/${id}`),
} getNtfy: () => request('GET', '/ntfy-settings'),
} updateNtfy: (body) => request('PUT', '/ntfy-settings', body),
testNtfy: () => request('POST', '/ntfy-settings/test'),
getBackupCfg: () => request('GET', '/backups/settings'),
updateBackupCfg:(body) => request('PUT', '/backups/settings', body),
listBackups: () => request('GET', '/backups'),
runBackup: () => request('POST', '/backups/run'),
restoreBackup: (f, scope) => request('POST', `/backups/${encodeURIComponent(f)}/restore`, { scope }),
deleteBackup: (f) => request('DELETE', `/backups/${encodeURIComponent(f)}`),
resetEntries: () => request('POST', '/reset/entries'),
};
async function toggleUser(id, disable) { // ── Helpers ────────────────────────────────────────────────────────────────
try {
if (disable) await API.admin.disable(id); function fmtDateTime(iso) {
else await API.admin.enable(id); if (!iso) return '';
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return '';
return d.toLocaleString(undefined, {
year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit',
});
}
function fmtBytes(n) {
if (n < 1024) return `${n} B`;
const units = ['KB', 'MB', 'GB'];
let v = n, i = -1;
do { v /= 1024; i += 1; } while (v >= 1024 && i < units.length - 1);
return `${v.toFixed(1)} ${units[i]}`;
}
function alertHtml(text, type) {
const cls = type === 'success' ? 'alert-success' : 'alert-error';
return `<div class="alert ${cls}">${escHtml(text)}</div>`;
}
function setMsg(id, text, type) {
const el = document.getElementById(id);
if (el) el.innerHTML = text ? alertHtml(text, type) : '';
}
// "Type X to arm, then click" confirm widget for destructive actions.
function confirmWidget(id, word, label) {
return `
<div class="admin-confirm">
<input type="text" id="${id}-input" placeholder="${escHtml(word)}" autocomplete="off"
data-word="${escHtml(word)}" oninput="Admin.armConfirm('${id}')" />
<button class="btn btn-sm btn-danger" id="${id}-btn" disabled>${escHtml(label)}</button>
</div>`;
}
function armConfirm(id) {
const input = document.getElementById(`${id}-input`);
const btn = document.getElementById(`${id}-btn`);
btn.disabled = input.value.trim().toLowerCase() !== input.dataset.word;
}
async function runConfirm(id, fn) {
const input = document.getElementById(`${id}-input`);
const btn = document.getElementById(`${id}-btn`);
if (btn.disabled) return;
const label = btn.textContent;
btn.disabled = true;
input.disabled = true;
btn.textContent = 'Working…';
try {
await fn();
input.value = '';
} finally {
input.disabled = false;
btn.textContent = label;
armConfirm(id);
}
}
// ── Tabs ───────────────────────────────────────────────────────────────────
function showTab(name) {
if (!TABS.includes(name)) name = 'users';
history.replaceState(null, '', `#${name}`);
document.querySelectorAll('.tab').forEach(t => t.classList.toggle('active', t.dataset.tab === name));
const content = document.getElementById('tab-content');
content.innerHTML = '<p class="admin-muted">Loading…</p>';
({ users: renderUsersTab, notifications: renderNotificationsTab,
backups: renderBackupsTab, reset: renderResetTab })[name]();
}
// ── Users ──────────────────────────────────────────────────────────────────
let users = [];
let tempPasswords = {};
let deleteTarget = null;
async function renderUsersTab() {
document.getElementById('tab-content').innerHTML = `
<div id="users-msg"></div>
<div class="section-header">
<input type="text" id="user-search" placeholder="Search users…" oninput="Admin.renderUserRows()" style="max-width:320px" />
<button class="btn btn-ghost btn-sm" onclick="Admin.loadUsers()">Refresh</button>
</div>
<div class="table-wrap">
<table>
<thead>
<tr><th>Display Name</th><th>Email</th><th>Entries</th><th>Status</th><th>Joined</th><th>Actions</th></tr>
</thead>
<tbody id="users-body"><tr class="empty-row"><td colspan="6">Loading…</td></tr></tbody>
</table>
</div>`;
await loadUsers(); await loadUsers();
} catch (err) {
showMsg(err.message, 'error');
} }
}
async function impersonateUser(id) { async function loadUsers() {
try { try {
const data = await API.admin.impersonate(id); users = await api.listUsers();
Auth.saveToken(data.access_token); renderUserRows();
const user = await API.users.me(); } catch (err) {
Auth.saveUser(user); const body = document.getElementById('users-body');
window.location.href = '/dashboard.html'; if (body) body.innerHTML = '<tr class="empty-row"><td colspan="6">Failed to load users.</td></tr>';
} catch (err) { setMsg('users-msg', err.message, 'error');
showMsg(err.message, 'error'); }
} }
}
function showDeleteModal(id, name) { function renderUserRows() {
deleteTargetId = id; const tbody = document.getElementById('users-body');
document.getElementById('delete-username').textContent = name; if (!tbody) return;
document.getElementById('delete-modal').style.display = 'flex'; const q = (document.getElementById('user-search')?.value || '').trim().toLowerCase();
} const filtered = users.filter(u =>
!q || u.email.toLowerCase().includes(q) || (u.display_name || '').toLowerCase().includes(q));
function hideDeleteModal() { if (!filtered.length) {
document.getElementById('delete-modal').style.display = 'none'; tbody.innerHTML = `<tr class="empty-row"><td colspan="6">${users.length ? 'No matching users.' : 'No users found.'}</td></tr>`;
deleteTargetId = null; return;
} }
async function submitDelete() { tbody.innerHTML = filtered.map(u => {
try { const status = u.is_disabled
await API.admin.delete(deleteTargetId); ? '<span class="badge badge-disabled">Disabled</span>'
hideDeleteModal(); : '<span class="badge badge-active">Active</span>';
showMsg('User deleted.', 'success'); const toggle = u.is_disabled
await loadUsers(); ? `<button class="btn btn-sm btn-primary" onclick="Admin.toggleUser(${u.id}, false)">Enable</button>`
} catch (err) { : `<button class="btn btn-sm btn-ghost" onclick="Admin.toggleUser(${u.id}, true)">Disable</button>`;
hideDeleteModal(); const temp = tempPasswords[u.id]
showMsg(err.message, 'error'); ? `<tr><td colspan="6"><div class="temp-pw"><code>${escHtml(tempPasswords[u.id])}</code>
<span>shown once — relay this to ${escHtml(u.email)}</span></div></td></tr>`
: '';
return `<tr${u.is_disabled ? ' style="opacity:.6"' : ''}>
<td><strong>${escHtml(u.display_name || u.email)}</strong></td>
<td>${escHtml(u.email)}</td>
<td>${u.entry_count}</td>
<td>${status}</td>
<td>${new Date(u.created_at).toLocaleDateString()}</td>
<td style="display:flex;gap:0.35rem;flex-wrap:wrap">
<button class="btn btn-sm btn-ghost" onclick="Admin.resetPassword(${u.id})">Reset PW</button>
${toggle}
<button class="btn btn-sm btn-danger" onclick="Admin.showDeleteModal(${u.id})">Delete</button>
</td>
</tr>${temp}`;
}).join('');
} }
}
function showMsg(text, type) { async function resetPassword(id) {
const el = document.getElementById('msg'); const u = users.find(x => x.id === id);
if (!el) return; if (!u || !confirm(`Reset password for ${u.email}? A new temporary password will be generated.`)) return;
const cls = type === 'success' ? 'alert-success' : 'alert-error'; try {
el.innerHTML = `<div class="alert ${cls}" style="margin-bottom:1rem">${escHtml(text)}</div>`; const { temp_password } = await api.resetPassword(id);
if (type === 'success') setTimeout(() => { el.innerHTML = ''; }, 3000); tempPasswords[id] = temp_password;
} await loadUsers();
} catch (err) {
setMsg('users-msg', err.message, 'error');
}
}
document.addEventListener('click', (e) => { async function toggleUser(id, disable) {
if (e.target.id === 'reset-modal') hideResetModal(); try {
if (e.target.id === 'delete-modal') hideDeleteModal(); await (disable ? api.disableUser(id) : api.enableUser(id));
}); await loadUsers();
} catch (err) {
setMsg('users-msg', err.message, 'error');
}
}
function showDeleteModal(id) {
deleteTarget = users.find(x => x.id === id) || null;
if (!deleteTarget) return;
document.getElementById('delete-email').textContent = deleteTarget.email;
document.getElementById('delete-confirm').value = '';
document.getElementById('delete-confirm').placeholder = deleteTarget.email;
document.getElementById('delete-submit').disabled = true;
document.getElementById('delete-msg').innerHTML = '';
document.getElementById('delete-modal').style.display = 'flex';
document.getElementById('delete-confirm').focus();
}
function hideDeleteModal() {
document.getElementById('delete-modal').style.display = 'none';
deleteTarget = null;
}
function onDeleteConfirmInput() {
const v = document.getElementById('delete-confirm').value;
document.getElementById('delete-submit').disabled = !deleteTarget || v !== deleteTarget.email;
}
async function submitDelete() {
if (!deleteTarget || document.getElementById('delete-confirm').value !== deleteTarget.email) return;
const btn = document.getElementById('delete-submit');
btn.disabled = true;
btn.textContent = 'Deleting…';
try {
await api.deleteUser(deleteTarget.id);
hideDeleteModal();
setMsg('users-msg', 'User deleted.', 'success');
await loadUsers();
} catch (err) {
document.getElementById('delete-msg').innerHTML = alertHtml(err.message, 'error');
btn.disabled = false;
} finally {
btn.textContent = 'Delete permanently';
}
}
// ── Notifications ──────────────────────────────────────────────────────────
async function renderNotificationsTab() {
let cfg;
try {
cfg = await api.getNtfy();
} catch (err) {
document.getElementById('tab-content').innerHTML = alertHtml(err.message, 'error');
return;
}
document.getElementById('tab-content').innerHTML = `
<div class="card admin-card">
<h3 class="card-title">Admin push notifications</h3>
<p class="admin-muted">Sent via ntfy for new registrations, admin logins and lockouts, user changes, resets and restores. Token auth only.</p>
<div class="form-group">
<label for="ntfy-server">Server URL</label>
<input type="text" id="ntfy-server" placeholder="https://ntfy.sh" value="${escHtml(cfg.ntfy_server_url || '')}" />
</div>
<div class="form-group">
<label for="ntfy-topic">Topic</label>
<input type="text" id="ntfy-topic" placeholder="my-secret-admin-topic" value="${escHtml(cfg.ntfy_topic || '')}" />
</div>
<div class="form-group">
<label for="ntfy-token">Access token <span id="ntfy-token-hint">${cfg.has_token ? '(configured — leave blank to keep)' : ''}</span></label>
<input type="password" id="ntfy-token" autocomplete="new-password" placeholder="${cfg.has_token ? '••••••••' : 'tk_…'}" />
</div>
<div id="ntfy-msg"></div>
<div style="display:flex;gap:0.5rem">
<button class="btn btn-primary" id="ntfy-save" onclick="Admin.saveNtfy()">Save</button>
<button class="btn btn-ghost" id="ntfy-test" onclick="Admin.testNtfy()">Send test</button>
</div>
</div>`;
}
async function saveNtfy() {
const btn = document.getElementById('ntfy-save');
setMsg('ntfy-msg', '');
btn.disabled = true;
btn.textContent = 'Saving…';
try {
const body = {
ntfy_server_url: document.getElementById('ntfy-server').value.trim(),
ntfy_topic: document.getElementById('ntfy-topic').value.trim(),
};
const token = document.getElementById('ntfy-token').value;
if (token) body.ntfy_token = token;
const updated = await api.updateNtfy(body);
const tokenInput = document.getElementById('ntfy-token');
tokenInput.value = '';
tokenInput.placeholder = updated.has_token ? '••••••••' : 'tk_…';
document.getElementById('ntfy-token-hint').textContent = updated.has_token ? '(configured — leave blank to keep)' : '';
setMsg('ntfy-msg', 'Saved.', 'success');
} catch (err) {
setMsg('ntfy-msg', err.message, 'error');
} finally {
btn.disabled = false;
btn.textContent = 'Save';
}
}
async function testNtfy() {
const btn = document.getElementById('ntfy-test');
setMsg('ntfy-msg', '');
btn.disabled = true;
btn.textContent = 'Sending…';
try {
await api.testNtfy();
setMsg('ntfy-msg', 'Test notification sent — check your device!', 'success');
} catch (err) {
setMsg('ntfy-msg', err.message, 'error');
} finally {
btn.disabled = false;
btn.textContent = 'Send test';
}
}
// ── Backups ────────────────────────────────────────────────────────────────
let backupFiles = [];
async function renderBackupsTab() {
let cfg;
try {
cfg = await api.getBackupCfg();
} catch (err) {
document.getElementById('tab-content').innerHTML = alertHtml(err.message, 'error');
return;
}
const hourOpts = Array.from({ length: 24 }, (_, h) =>
`<option value="${h}"${h === cfg.backup_hour ? ' selected' : ''}>${String(h).padStart(2, '0')}:00</option>`).join('');
const dayOpts = WEEKDAYS.map((w, i) =>
`<option value="${i}"${i === cfg.backup_weekday ? ' selected' : ''}>${w}</option>`).join('');
document.getElementById('tab-content').innerHTML = `
<div class="card admin-card">
<h3 class="card-title">Backup schedule</h3>
<p class="admin-muted">Runs a full database dump into /backups, the NFS share set via BACKUP_NFS_HOST / BACKUP_NFS_PATH in .env. All times are UTC.</p>
<label class="admin-check">
<input type="checkbox" id="bk-enabled"${cfg.backup_enabled ? ' checked' : ''} /> Enable scheduled backups
</label>
<div class="admin-grid">
<div class="form-group">
<label for="bk-frequency">Frequency</label>
<select id="bk-frequency" onchange="Admin.onFrequencyChange()">
<option value="daily"${cfg.backup_frequency === 'daily' ? ' selected' : ''}>Daily</option>
<option value="weekly"${cfg.backup_frequency === 'weekly' ? ' selected' : ''}>Weekly</option>
</select>
</div>
<div class="form-group">
<label for="bk-hour">Hour (UTC)</label>
<select id="bk-hour">${hourOpts}</select>
</div>
<div class="form-group" id="bk-weekday-group"${cfg.backup_frequency === 'weekly' ? '' : ' style="display:none"'}>
<label for="bk-weekday">Day of week</label>
<select id="bk-weekday">${dayOpts}</select>
</div>
<div class="form-group">
<label for="bk-retention">Keep last N backups</label>
<input type="number" id="bk-retention" min="1" max="365" value="${cfg.backup_retention}" />
</div>
<div class="form-group">
<label for="bk-location">Subfolder (optional)</label>
<input type="text" id="bk-location" placeholder="e.g. nightly" value="${escHtml(cfg.backup_location || '')}" />
</div>
</div>
<div id="bk-save-msg"></div>
<button class="btn btn-primary btn-sm" id="bk-save" onclick="Admin.saveBackupCfg()">Save schedule</button>
<p class="admin-muted" id="bk-last" style="margin-top:1rem"></p>
</div>
<div class="card admin-card">
<h3 class="card-title">Backup now</h3>
<p class="admin-muted">Run an immediate backup outside the schedule.</p>
<button class="btn btn-primary btn-sm" id="bk-run" onclick="Admin.runBackup()">Backup now</button>
<div id="bk-run-msg" style="margin-top:.75rem"></div>
</div>
<div class="section-header" style="margin-top:1.5rem"><h2>Backup files</h2></div>
<div id="bk-files"><p class="admin-muted">Loading…</p></div>`;
renderLastBackup(cfg);
await loadBackupFiles();
}
function renderLastBackup(cfg) {
const el = document.getElementById('bk-last');
if (!el) return;
if (!cfg.last_backup_at) { el.textContent = 'No backups have run yet.'; return; }
el.innerHTML = `Last backup: ${escHtml(fmtDateTime(cfg.last_backup_at))} — ` + (cfg.last_backup_status === 'success'
? '<span class="text-success">success</span>'
: `<span class="text-danger">failed: ${escHtml(cfg.last_backup_error || '')}</span>`);
}
function onFrequencyChange() {
const weekly = document.getElementById('bk-frequency').value === 'weekly';
document.getElementById('bk-weekday-group').style.display = weekly ? '' : 'none';
}
async function saveBackupCfg() {
const btn = document.getElementById('bk-save');
setMsg('bk-save-msg', '');
btn.disabled = true;
btn.textContent = 'Saving…';
try {
const updated = await api.updateBackupCfg({
backup_enabled: document.getElementById('bk-enabled').checked,
backup_frequency: document.getElementById('bk-frequency').value,
backup_hour: Number(document.getElementById('bk-hour').value),
backup_weekday: Number(document.getElementById('bk-weekday').value),
backup_retention: Number(document.getElementById('bk-retention').value),
backup_location: document.getElementById('bk-location').value,
});
document.getElementById('bk-location').value = updated.backup_location || '';
setMsg('bk-save-msg', 'Saved.', 'success');
renderLastBackup(updated);
await loadBackupFiles();
} catch (err) {
setMsg('bk-save-msg', err.message, 'error');
} finally {
btn.disabled = false;
btn.textContent = 'Save schedule';
}
}
async function runBackup() {
const btn = document.getElementById('bk-run');
setMsg('bk-run-msg', '');
btn.disabled = true;
btn.textContent = 'Backing up…';
try {
const r = await api.runBackup();
setMsg('bk-run-msg', `Created ${r.filename} (${fmtBytes(r.size_bytes)}).`, 'success');
renderLastBackup(await api.getBackupCfg());
await loadBackupFiles();
} catch (err) {
setMsg('bk-run-msg', err.message, 'error');
api.getBackupCfg().then(renderLastBackup).catch(() => {});
} finally {
btn.disabled = false;
btn.textContent = 'Backup now';
}
}
async function loadBackupFiles() {
const el = document.getElementById('bk-files');
if (!el) return;
try {
backupFiles = await api.listBackups();
} catch (err) {
el.innerHTML = alertHtml('Failed to load backup files: ' + err.message, 'error');
return;
}
if (!backupFiles.length) {
el.innerHTML = '<p class="admin-muted"><em>No backups yet.</em></p>';
return;
}
el.innerHTML = backupFiles.map((f, i) => `
<div class="card admin-card admin-file">
<div class="admin-file-head">
<div>
<code>${escHtml(f.filename)}</code>
<div class="admin-muted">${fmtBytes(f.size_bytes)} · ${escHtml(fmtDateTime(f.created_at))}</div>
</div>
<button class="btn btn-sm btn-ghost" id="bk-del-${i}" onclick="Admin.deleteBackup(${i})">Delete</button>
</div>
<div class="admin-restore">
<div>
<label>Type <code>restore entries</code></label>
${confirmWidget(`rs-e-${i}`, 'restore entries', 'Restore entries only')}
</div>
<div>
<label>Type <code>restore all</code></label>
${confirmWidget(`rs-a-${i}`, 'restore all', 'Restore all data')}
</div>
</div>
<div id="bk-row-msg-${i}"></div>
</div>`).join('');
backupFiles.forEach((f, i) => {
document.getElementById(`rs-e-${i}-btn`).onclick = () => restore(i, 'entries');
document.getElementById(`rs-a-${i}-btn`).onclick = () => restore(i, 'all');
});
}
async function restore(i, scope) {
const f = backupFiles[i];
const id = scope === 'all' ? `rs-a-${i}` : `rs-e-${i}`;
setMsg(`bk-row-msg-${i}`, '');
await runConfirm(id, async () => {
try {
await api.restoreBackup(f.filename, scope);
setMsg(`bk-row-msg-${i}`, `Restored ${scope === 'all' ? 'all data' : 'entries'}.`, 'success');
} catch (err) {
setMsg(`bk-row-msg-${i}`, err.message, 'error');
}
});
}
async function deleteBackup(i) {
const f = backupFiles[i];
if (!confirm(`Delete backup file "${f.filename}"? This cannot be undone.`)) return;
const btn = document.getElementById(`bk-del-${i}`);
btn.disabled = true;
btn.textContent = 'Deleting…';
try {
await api.deleteBackup(f.filename);
await loadBackupFiles();
} catch (err) {
setMsg(`bk-row-msg-${i}`, 'Delete failed: ' + err.message, 'error');
btn.disabled = false;
btn.textContent = 'Delete';
}
}
// ── Reset ──────────────────────────────────────────────────────────────────
function renderResetTab() {
document.getElementById('tab-content').innerHTML = `
<div class="alert alert-error">
<strong>Destructive actions</strong><br />
These run across every user's data and cannot be undone. User accounts, passwords, profile
settings and admin settings are always kept. Each one automatically runs a fresh backup first
and refuses to proceed if that backup fails.
</div>
<div class="card admin-card">
<h3 class="card-title">Reset all entries</h3>
<p class="admin-muted">Permanently delete every bottle entry (adds and removes) for every user — each bottle starts empty again.</p>
<label>Type <code>reset entries</code> to confirm</label>
${confirmWidget('reset-entries', 'reset entries', 'Reset all entries')}
<div id="reset-entries-msg" style="margin-top:.75rem"></div>
</div>`;
document.getElementById('reset-entries-btn').onclick = () => {
setMsg('reset-entries-msg', '');
runConfirm('reset-entries', async () => {
try {
const r = await api.resetEntries();
setMsg('reset-entries-msg',
`Deleted ${r.entries_deleted} entr${r.entries_deleted === 1 ? 'y' : 'ies'}. Safety backup: ${r.backup_filename}.`,
'success');
} catch (err) {
setMsg('reset-entries-msg', err.message, 'error');
}
});
};
}
// ── Init ───────────────────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', () => {
if (!localStorage.getItem(TOKEN_KEY)) { window.location.href = '/login.html'; return; }
showTab(location.hash.slice(1));
});
document.addEventListener('click', (e) => {
if (e.target.id === 'delete-modal') hideDeleteModal();
});
return {
signOut, showTab, armConfirm,
loadUsers, renderUserRows, resetPassword, toggleUser,
showDeleteModal, hideDeleteModal, onDeleteConfirmInput, submitDelete,
saveNtfy, testNtfy,
onFrequencyChange, saveBackupCfg, runBackup, deleteBackup,
};
})();
-10
View File
@@ -66,15 +66,5 @@ const API = (() => {
public: { public: {
stats: () => request('GET', '/public/stats'), stats: () => request('GET', '/public/stats'),
}, },
admin: {
listUsers: () => request('GET', '/admin/users'),
createUser: (body) => request('POST', '/admin/users', body),
resetPassword: (id, body) => request('POST', `/admin/users/${id}/reset-password`, body),
disable: (id) => request('POST', `/admin/users/${id}/disable`, {}),
enable: (id) => request('POST', `/admin/users/${id}/enable`, {}),
delete: (id) => request('DELETE', `/admin/users/${id}`),
impersonate: (id) => request('POST', `/admin/users/${id}/impersonate`, {}),
unimpersonate: () => request('POST', '/admin/unimpersonate', {}),
},
}; };
})(); })();
+6 -30
View File
@@ -55,28 +55,17 @@ const Auth = (() => {
try { user = await API.users.me(); saveUser(user); } catch (_) {} try { user = await API.users.me(); saveUser(user); } catch (_) {}
} }
const payload = _decodePayload();
const isImpersonating = !!(payload && payload.admin_id);
navLinksEl.innerHTML = ` navLinksEl.innerHTML = `
<a href="/dashboard.html" class="btn btn-ghost btn-sm${activePage === 'dashboard' ? ' active' : ''}">My Bottle</a> <a href="/dashboard.html" class="btn btn-ghost btn-sm${activePage === 'dashboard' ? ' active' : ''}">My Bottle</a>
<a href="/log.html" class="btn btn-ghost btn-sm${activePage === 'log' ? ' active' : ''}">Log Entry</a> <a href="/log.html" class="btn btn-ghost btn-sm${activePage === 'log' ? ' active' : ''}">Log Entry</a>
`; `;
if (isImpersonating) { navUserEl.innerHTML = `
navUserEl.innerHTML = ` <span class="nav-username">${escHtml(user?.display_name || user?.email || 'Account')}</span>
<span class="nav-impersonating">Viewing as <strong>${escHtml(user?.display_name || user?.email || 'User')}</strong></span> <button onclick="Auth.showSettingsModal()" class="btn btn-sm btn-ghost" title="Settings">&#9881;</button>
<button onclick="Auth.returnToAdmin()" class="btn btn-sm btn-amber">&#8617; Return to Admin</button> <button onclick="Auth.logout()" class="btn btn-sm btn-ghost">Logout</button>
`; `;
} else { _injectSettingsModal(user);
navUserEl.innerHTML = `
<span class="nav-username">${escHtml(user?.display_name || user?.email || 'Account')}</span>
${user?.is_admin ? '<a href="/admin.html" class="btn btn-sm btn-ghost">Admin</a>' : ''}
<button onclick="Auth.showSettingsModal()" class="btn btn-sm btn-ghost" title="Settings">&#9881;</button>
<button onclick="Auth.logout()" class="btn btn-sm btn-ghost">Logout</button>
`;
_injectSettingsModal(user);
}
} else { } else {
navLinksEl.innerHTML = ''; navLinksEl.innerHTML = '';
navUserEl.innerHTML = `<a href="/login.html" class="btn btn-primary btn-sm">Login</a>`; navUserEl.innerHTML = `<a href="/login.html" class="btn btn-primary btn-sm">Login</a>`;
@@ -229,22 +218,9 @@ const Auth = (() => {
if (type === 'success') setTimeout(() => { el.innerHTML = ''; }, 3000); if (type === 'success') setTimeout(() => { el.innerHTML = ''; }, 3000);
} }
async function returnToAdmin() {
try {
const data = await API.post('/admin/unimpersonate', {});
saveToken(data.access_token);
const user = await API.users.me();
saveUser(user);
window.location.href = '/admin.html';
} catch (_) {
logout();
}
}
return { return {
getToken, saveToken, getUser, saveUser, getToken, saveToken, getUser, saveUser,
logout, isLoggedIn, requireAuth, redirectIfLoggedIn, renderNav, logout, isLoggedIn, requireAuth, redirectIfLoggedIn, renderNav,
showSettingsModal, hideSettingsModal, detectTimezone, saveProfile, submitPasswordChange, showSettingsModal, hideSettingsModal, detectTimezone, saveProfile, submitPasswordChange,
returnToAdmin,
}; };
})(); })();
+41 -10
View File
@@ -28,7 +28,7 @@
<form id="login-form"> <form id="login-form">
<div class="form-group"> <div class="form-group">
<label for="email">Email</label> <label for="email">Email</label>
<input type="email" id="email" autocomplete="email" required placeholder="[email protected]" /> <input type="text" id="email" autocomplete="username" required placeholder="[email protected]" />
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="password">Password</label> <label for="password">Password</label>
@@ -60,19 +60,50 @@ document.addEventListener('DOMContentLoaded', () => {
btn.disabled = true; btn.disabled = true;
btn.textContent = 'Signing in…'; btn.textContent = 'Signing in…';
const email = document.getElementById('email').value.trim();
const password = document.getElementById('password').value;
try { try {
const email = document.getElementById('email').value.trim(); // Raw fetch (not API.auth.login) so a 401 doesn't trigger the global sign-out redirect.
const password = document.getElementById('password').value; const res = await fetch('/api/auth/login', {
const data = await API.auth.login(email, password); method: 'POST',
Auth.saveToken(data.access_token); headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
const data = await res.json().catch(() => null);
// Pre-fetch user info so nav renders immediately if (res.ok) {
const user = await API.users.me(); Auth.saveToken(data.access_token);
Auth.saveUser(user); // Pre-fetch user info so nav renders immediately
const user = await API.users.me();
Auth.saveUser(user);
window.location.href = '/index.html';
return;
}
window.location.href = '/index.html'; // A rejected normal login might be the out-of-band admin account.
if (res.status === 401 || res.status === 422) {
const adminRes = await fetch('/api/admin/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: email, password }),
});
if (adminRes.ok) {
const adminData = await adminRes.json();
localStorage.setItem('bb_admin_token', adminData.access_token);
window.location.href = '/admin.html?v=2';
return;
}
if (adminRes.status === 429) {
const adminErr = await adminRes.json().catch(() => null);
throw new Error(adminErr?.detail || 'Too many attempts. Try again later.');
}
throw new Error('Invalid credentials');
}
throw new Error(data?.detail || `HTTP ${res.status}`);
} catch (err) { } catch (err) {
alert.innerHTML = `<div class="alert alert-error">${err.message}</div>`; alert.innerHTML = `<div class="alert alert-error">${escHtml(err.message)}</div>`;
btn.disabled = false; btn.disabled = false;
btn.textContent = 'Sign In'; btn.textContent = 'Sign In';
} }
+2
View File
@@ -15,6 +15,8 @@ server {
add_header X-Content-Type-Options "nosniff" always; add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always; add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always; add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# Revalidate on every load so updated pages/JS reach browsers immediately.
add_header Cache-Control "no-cache" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self';" always; add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self';" always;
if ($request_method = TRACE) { if ($request_method = TRACE) {