feat(minecraft): add server service and modular FastAPI web admin panel

- Deploys Paper MC Minecraft Java server in offline-mode on host port 25565.
- Deploys a FastAPI-based Web Admin panel on minecraft.arch-services.mywire.org (port 80/443).
- Implements a layered FastAPI architecture (routers, schemas, services, database models).
- Calculates deterministic version 3 Minecraft player UUIDs for player responses.
- Resolves cross-container permission deadlocks by running the web container as UID 1000:1000.
- Implements Write-Ahead Logging (WAL) and busy timeout to prevent SQLite concurrency lockouts.
- Adds asynchronous database polling and API readiness middleware to prevent DB file initialization races.
- Injects JWT_SECRET to persist administrator web sessions across restarts.
- Integrates Minecraft service commands into the appctl shell management script.
- Documents all containerization decisions in minecraft/adr.md.
This commit is contained in:
kiskaadee committed 2026-08-11 18:08:27 -05:00
1 parent c3bcaf1992
commit f5429960b4
14 files changed
+1804 -1

No files matched your search

+3 -1
View File
@@ -109,6 +109,8 @@ load_app_env() {
export PORT="${MINECRAFT_PORT:-25565}"
export PROXY_NETWORK="$PROXY_NETWORK"
export TZ="${TZ:-UTC}"
export MINECRAFT_DOMAIN="${MINECRAFT_DOMAIN:-minecraft.${DOMAIN_SUFFIX:-arch-services.mywire.org}}"
export MINECRAFT_JWT_SECRET="${MINECRAFT_JWT_SECRET:-supersecurejwtsecretvalueforlocaldevelopmentonly}"
;;
*)
echo "Unknown service: $app"
@@ -211,7 +213,7 @@ case "$COMMAND" in
if [ -z "$APP" ]; then echo "Error: Service name required"; exit 1; fi
load_app_env "$APP"
echo "=== Active Environment Variables for $APP ==="
env | grep -E "^(PROXY_NETWORK|CERT_RESOLVER|DOMAIN|SERVICE_DOMAIN|SERVICE_NAME|CONTAINER_NAME|IMAGE_TAG|TZ|PUID|PGID|MEDIA_PATH|HTTP_ENTRYPOINT|HTTPS_ENTRYPOINT|RATE_LIMIT_AVG|RATE_LIMIT_BURST|APP_PORT|SOCKET_PROXY_NETWORK|TURSO_DATABASE_URL|TURSO_AUTH_TOKEN|DOCKER_HOST|MONGO_ROOT_USERNAME|MONGO_ROOT_PASSWORD|MONGO_DOMAIN|POSTGRES_USER|POSTGRES_PASSWORD|POSTGRES_DB|POSTGRES_DOMAIN|OLLAMA_API_KEY|REPLICAS|OLLAMA_DATA_VOLUME|GITEA_VERSION|GITEA_DOMAIN|GITEA_SSH_DOMAIN|GITEA_AUTH_MIDDLEWARE|SSH_DOMAIN|DATA_PATH|AUTH_MIDDLEWARE|HTTPS_REDIRECT_MIDDLEWARE|PROJECT_PATH|DOCS_PROJECT_PATH|DOCS_DOMAIN|MINECRAFT_CONTAINER_NAME|MINECRAFT_TYPE|MINECRAFT_VERSION|MINECRAFT_MEMORY|MINECRAFT_PORT|MINECRAFT_DOMAIN|PORT|TYPE|VERSION|MEMORY)" | sort
env | grep -E "^(PROXY_NETWORK|CERT_RESOLVER|DOMAIN|SERVICE_DOMAIN|SERVICE_NAME|CONTAINER_NAME|IMAGE_TAG|TZ|PUID|PGID|MEDIA_PATH|HTTP_ENTRYPOINT|HTTPS_ENTRYPOINT|RATE_LIMIT_AVG|RATE_LIMIT_BURST|APP_PORT|SOCKET_PROXY_NETWORK|TURSO_DATABASE_URL|TURSO_AUTH_TOKEN|DOCKER_HOST|MONGO_ROOT_USERNAME|MONGO_ROOT_PASSWORD|MONGO_DOMAIN|POSTGRES_USER|POSTGRES_PASSWORD|POSTGRES_DB|POSTGRES_DOMAIN|OLLAMA_API_KEY|REPLICAS|OLLAMA_DATA_VOLUME|GITEA_VERSION|GITEA_DOMAIN|GITEA_SSH_DOMAIN|GITEA_AUTH_MIDDLEWARE|SSH_DOMAIN|DATA_PATH|AUTH_MIDDLEWARE|HTTPS_REDIRECT_MIDDLEWARE|PROJECT_PATH|DOCS_PROJECT_PATH|DOCS_DOMAIN|MINECRAFT_CONTAINER_NAME|MINECRAFT_TYPE|MINECRAFT_VERSION|MINECRAFT_MEMORY|MINECRAFT_PORT|MINECRAFT_DOMAIN|PORT|TYPE|VERSION|MEMORY|MINECRAFT_JWT_SECRET|JWT_SECRET)" | sort
;;
*)
show_help
+40
View File
@@ -0,0 +1,40 @@
# Architecture Decision Record (ADR): Security, Concurrency, and Initialization for Web Admin Panel
## Status
Approved
## Context
When running the FastAPI Web Admin Panel container alongside the Paper MC Java container, several system-level issues arose due to shared resource limits, permission boundaries, and asynchronous start sequences:
1. **Cross-Container Permission Deadlock**: The Python FastAPI container runs as `root` by default, whereas the Minecraft server container drops privileges to run as `1000:1000`. When FastAPI writes to the SQLite database, journaling files (`authme.db-journal`, `-wal`, or `-shm`) are created under `root` ownership. The Java server then crashes with a `Permission denied` error when trying to access or clear these database locks.
2. **SQLite Concurrency and Write-Locking**: Multiple processes (the Python API and the Java Minecraft process) access a single SQLite file (`authme.db`) concurrently. This can lead to database locking exceptions (`database is locked`) during write operations.
3. **Database Initialization Race Condition**: If the FastAPI container initializes faster than the Java Minecraft container (which takes up to a minute to download Paper, fetch plugins, and boot the JVM), FastAPI's `init_db()` will connect to a non-existent `authme.db` path, causing SQLite to write a blank database file. When the Java server boots later, it detects this empty database and fails or crashes due to unexpected schema states.
4. **Ephemeral Session State**: The JWT secret was dynamically generated on FastAPI startup. If the container crashed, restarted, or was redeployed, all active user sessions were invalidated, forcing administrators to sign in again.
---
## Decisions
### 1. Unified Container Privileges (Permissions)
We will run the FastAPI web application as `user: "1000:1000"` within `docker-compose.yml`.
* **Reasoning**: This binds the Python process to the same UID/GID as the Minecraft server. Any file written to the shared volume (including SQLite rollback journals) inherits `1000:1000` permissions, resolving any filesystem permission deadlocks.
### 2. SQLite Write-Ahead Logging & Busy Timeout (Concurrency)
We will configure the SQLite connection in `database.py` to enable **Write-Ahead Logging (WAL)** and set a connection busy timeout of **5.0 seconds** (`5000` ms).
* **Reasoning**: WAL mode allows concurrent readers (e.g. players logging in, dashboard list requests) while a write is occurring, and the busy timeout ensures that if the database is temporarily locked, SQLite queues the write instead of failing immediately.
### 3. Asynchronous Schema Polling & 503 Middleware (Initialization)
We will replace the synchronous startup database migration call with an asynchronous background task.
* **Database Polling**: The background loop checks if the `authme.db` file exists and queries SQLite's `sqlite_master` metadata table to ensure the `authme` table exists (which confirms AuthMe has finished setting up the schema). Only then does the web panel run its migrations for auxiliary tables (`user_roles`, `reset_requests`) and mark the database state as `DB_READY`.
* **Readiness Middleware**: Added a FastAPI middleware that intercepts all `/api/` traffic and returns a HTTP `503 Service Unavailable` error if `DB_READY` is still `False`.
### 4. Session Persistence (JWT Secret Injection)
We will inject a static `JWT_SECRET` via the `docker-compose.yml` environment block, mapped to `MINECRAFT_JWT_SECRET` and managed via `.env` or NixOS secrets.
* **Reasoning**: Preserves cryptographical token validity across container updates and restarts.
---
## Consequences
* **Permissions**: Zero file ownership conflict when containers update or write to shared volumes.
* **Parallel Performance**: Excellent multi-process read/write safety under SQLite without locking faults.
* **Resilient Startup**: The FastAPI web admin is start-order independent. It boots gracefully and awaits the Minecraft container's schema preparation before initializing itself, protecting database sanity.
+25
View File
@@ -18,6 +18,31 @@ services:
networks:
- proxy
web:
build: ./web
container_name: minecraft-web-admin
user: "1000:1000"
restart: unless-stopped
environment:
- JWT_SECRET=${MINECRAFT_JWT_SECRET:-supersecurejwtsecretvalueforlocaldevelopmentonly}
volumes:
- ./data/plugins/AuthMe:/app/db:rw
networks:
- proxy
labels:
- "traefik.enable=true"
# HTTPS Router
- "traefik.http.routers.minecraft-web.rule=Host(`${MINECRAFT_DOMAIN}`)"
- "traefik.http.routers.minecraft-web.entrypoints=websecure"
- "traefik.http.routers.minecraft-web.tls=true"
- "traefik.http.routers.minecraft-web.service=minecraft-web-svc"
# HTTP to HTTPS Redirect
- "traefik.http.routers.minecraft-web-red.rule=Host(`${MINECRAFT_DOMAIN}`)"
- "traefik.http.routers.minecraft-web-red.entrypoints=web"
- "traefik.http.routers.minecraft-web-red.middlewares=https-redirect@docker"
# Service definition
- "traefik.http.services.minecraft-web-svc.loadbalancer.server.port=8000"
networks:
proxy:
name: ${PROXY_NETWORK:-proxy-net}
+14
View File
@@ -0,0 +1,14 @@
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY main.py database.py schemas.py services.py ./
COPY routers/ routers/
COPY templates/ templates/
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
+75
View File
@@ -0,0 +1,75 @@
import os
import sqlite3
DB_PATH = "/app/db/authme.db"
DB_READY = False
def get_db():
# Set a 5-second busy timeout for concurrent write queuing
conn = sqlite3.connect(DB_PATH, timeout=5.0)
# Enable Write-Ahead Logging (WAL) for concurrent read/write optimization
conn.execute("PRAGMA journal_mode=WAL;")
conn.row_factory = sqlite3.Row
return conn
def init_db():
conn = get_db()
cursor = conn.cursor()
# Create roles table if it doesn't exist
cursor.execute("""
CREATE TABLE IF NOT EXISTS user_roles (
username VARCHAR(255) PRIMARY KEY,
role VARCHAR(50) NOT NULL DEFAULT 'player'
)
""")
# Create reset requests table if it doesn't exist
cursor.execute("""
CREATE TABLE IF NOT EXISTS reset_requests (
username VARCHAR(255) PRIMARY KEY,
status VARCHAR(50) NOT NULL DEFAULT 'pending',
requested_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Seed default admins
cursor.execute("""
INSERT OR IGNORE INTO user_roles (username, role)
VALUES ('kiskaadee', 'admin')
""")
cursor.execute("""
INSERT OR IGNORE INTO user_roles (username, role)
VALUES ('admin', 'admin')
""")
conn.commit()
conn.close()
def check_db_ready() -> bool:
global DB_READY
if DB_READY:
return True
# Check if the database file exists first (non-blocking file check)
if not os.path.exists(DB_PATH):
return False
try:
# Check if authme table exists
conn = get_db()
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='authme'")
table_exists = cursor.fetchone() is not None
conn.close()
if table_exists:
# Run our auxiliary table initializations
init_db()
DB_READY = True
return True
except Exception:
# Ignore errors during initial boot phase
pass
return False
+39
View File
@@ -0,0 +1,39 @@
import os
import asyncio
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse
import database
from routers import auth, users, admin
app = FastAPI(title="Minecraft Identity Manager API")
# Include Routers
app.include_router(auth.router)
app.include_router(users.router)
app.include_router(admin.router)
# Readiness middleware to block API requests until database is ready
@app.middleware("http")
async def db_readiness_middleware(request: Request, call_next):
# Only intercept /api/ requests
if request.url.path.startswith("/api/") and not database.DB_READY:
return JSONResponse(
status_code=503,
content={"detail": "Authentication system is initializing, please try again shortly."}
)
return await call_next(request)
# Asynchronous background loop to poll database readiness
async def database_polling_loop():
while not database.check_db_ready():
await asyncio.sleep(2)
@app.on_event("startup")
async def on_startup():
asyncio.create_task(database_polling_loop())
@app.get("/", response_class=HTMLResponse)
def index():
templates_dir = "/app/templates"
with open(os.path.join(templates_dir, "index.html"), "r") as f:
return f.read()
+4
View File
@@ -0,0 +1,4 @@
fastapi>=0.100.0
uvicorn>=0.22.0
pyjwt>=2.7.0
python-multipart>=0.0.6
+1
View File
@@ -0,0 +1 @@
# Router Module Packager
+64
View File
@@ -0,0 +1,64 @@
from fastapi import APIRouter, Form, HTTPException, Depends, status
from typing import List, Optional
from schemas import CreateUserRequest, RoleChangeRequest
from services import PlayerService, ResetRequestService, require_admin
router = APIRouter(prefix="", tags=["admin"])
@router.post("/api/users", status_code=status.HTTP_201_CREATED)
def create_user(req: CreateUserRequest, current_user: dict = Depends(require_admin)):
username = req.username.strip()
if not username or len(username) < 3:
raise HTTPException(status_code=400, detail="Username must be at least 3 characters")
res = PlayerService.create_user(
username=username,
password_raw=req.password,
email=req.email,
role=req.role
)
return {"message": f"Player {username} created successfully", "user": res}
@router.delete("/api/users/{username}")
def delete_user(username: str, current_user: dict = Depends(require_admin)):
if username.lower() == current_user["username"].lower():
raise HTTPException(status_code=400, detail="Cannot delete your own account")
PlayerService.delete_user(username)
return {"message": f"Player {username} deleted successfully"}
@router.post("/api/users/{username}/role")
def change_role(username: str, req: RoleChangeRequest, current_user: dict = Depends(require_admin)):
if username.lower() == current_user["username"].lower():
raise HTTPException(status_code=400, detail="Cannot change your own role")
if req.role not in ["admin", "player"]:
raise HTTPException(status_code=400, detail="Invalid role. Must be 'admin' or 'player'")
PlayerService.update_role(username, req.role)
return {"message": f"Role for {username} updated to {req.role}"}
@router.get("/api/admin/reset-requests")
def list_reset_requests(current_user: dict = Depends(require_admin)):
return ResetRequestService.list_requests()
@router.post("/api/admin/reset-requests/{username}/resolve")
def resolve_reset_request(
username: str,
action: str = Form(...),
new_password: Optional[str] = Form(None),
current_user: dict = Depends(require_admin)
):
if action == "approve":
if not new_password or len(new_password) < 5:
raise HTTPException(status_code=400, detail="A valid new password is required to approve the reset")
PlayerService.update_password(username, new_password)
ResetRequestService.delete_request(username)
return {"message": f"Password reset for {username} approved and updated."}
elif action == "reject":
ResetRequestService.delete_request(username)
return {"message": f"Reset request for {username} rejected."}
else:
raise HTTPException(status_code=400, detail="Invalid action. Use 'approve' or 'reject'")
+38
View File
@@ -0,0 +1,38 @@
from fastapi import APIRouter, Response, HTTPException, status, Depends
from schemas import LoginRequest
from services import AuthService, PlayerService, get_current_user
router = APIRouter(prefix="/api", tags=["authentication"])
@router.post("/login")
def login(login_data: LoginRequest, response: Response):
username = login_data.username.strip()
password = login_data.password
user = PlayerService.get_user_by_username(username)
# We retrieve the raw password hash from player database to verify
if not user or not AuthService.verify_password(password, user["password"]):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid username or password")
# Generate token
token = AuthService.create_jwt_token(username)
response.set_cookie(
key="access_token",
value=token,
httponly=True,
max_age=43200, # 12 hours
samesite="lax"
)
return {"message": "Logged in successfully"}
@router.post("/logout")
def logout(response: Response):
response.delete_cookie("access_token")
return {"message": "Logged out successfully"}
@router.get("/me")
def get_me(current_user: dict = Depends(get_current_user)):
return current_user
+36
View File
@@ -0,0 +1,36 @@
from fastapi import APIRouter, HTTPException, Depends
from typing import List
from schemas import UserResponse, ChangePasswordRequest, ResetRequest
from services import PlayerService, ResetRequestService, get_current_user
router = APIRouter(prefix="/api", tags=["users"])
@router.get("/users", response_model=List[UserResponse])
def list_users(current_user: dict = Depends(get_current_user)):
players = PlayerService.list_all_users()
# Post-process for users who are not admins (mask email addresses)
for p in players:
if current_user["role"] != "admin" and p["username"].lower() != current_user["username"].lower():
p["email"] = "••••@••••.•••" if p.get("email") else None
return players
@router.post("/users/change-password")
def change_password(req: ChangePasswordRequest, current_user: dict = Depends(get_current_user)):
user = PlayerService.get_user_by_username(current_user["username"])
if not user or not PlayerService.AuthService.verify_password(req.old_password, user["password"]):
raise HTTPException(status_code=400, detail="Incorrect old password")
PlayerService.update_password(current_user["username"], req.new_password)
return {"message": "Password updated successfully"}
@router.post("/reset-request")
def request_password_reset(req: ResetRequest):
username = req.username.strip()
user = PlayerService.get_user_by_username(username)
if not user:
raise HTTPException(status_code=404, detail="Player username not found")
ResetRequestService.create_request(username)
return {"message": "Password reset request submitted. Please notify an administrator."}
+36
View File
@@ -0,0 +1,36 @@
from pydantic import BaseModel, EmailStr
from typing import Optional
class LoginRequest(BaseModel):
username: str
password: str
class UserResponse(BaseModel):
id: int
uuid: str
username: str
realname: str
email: Optional[str] = None
role: str
regdate: Optional[int] = None
class CreateUserRequest(BaseModel):
username: str
password: str
email: Optional[str] = None
role: str = "player"
class ChangePasswordRequest(BaseModel):
old_password: str
new_password: str
class ResetRequest(BaseModel):
username: str
class ResetRequestResponse(BaseModel):
username: str
status: str
requested_at: str
class RoleChangeRequest(BaseModel):
role: str
+232
View File
@@ -0,0 +1,232 @@
import os
import sqlite3
import secrets
import hashlib
import uuid
import jwt
import datetime
from typing import Optional, List
from fastapi import Request, Depends, HTTPException, status
from fastapi.security import APIKeyCookie
from database import get_db
JWT_SECRET = os.environ.get("JWT_SECRET", secrets.token_hex(32))
JWT_ALGORITHM = "HS256"
COOKIE_NAME = "access_token"
cookie_scheme = APIKeyCookie(name=COOKIE_NAME, auto_error=False)
class AuthService:
@staticmethod
def generate_salt() -> str:
return secrets.token_hex(8)
@staticmethod
def hash_password(password: str, salt: str) -> str:
pass_hash = hashlib.sha256(password.encode('utf-8')).hexdigest()
combined = pass_hash + salt
final_hash = hashlib.sha256(combined.encode('utf-8')).hexdigest()
return f"$SHA${salt}${final_hash}"
@staticmethod
def verify_password(password: str, authme_hash: str) -> bool:
try:
parts = authme_hash.split("$")
if len(parts) != 4 or parts[1] != "SHA":
return False
salt = parts[2]
stored_hash = parts[3]
pass_hash = hashlib.sha256(password.encode('utf-8')).hexdigest()
combined = pass_hash + salt
computed_hash = hashlib.sha256(combined.encode('utf-8')).hexdigest()
return secrets.compare_digest(computed_hash, stored_hash)
except Exception:
return False
@staticmethod
def create_jwt_token(username: str) -> str:
payload = {
"sub": username.lower(),
"exp": datetime.datetime.utcnow() + datetime.timedelta(hours=12)
}
return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
@staticmethod
def decode_jwt_token(token: str) -> Optional[str]:
try:
payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
return payload.get("sub")
except jwt.PyJWTError:
return None
class PlayerService:
@staticmethod
def calculate_offline_uuid(username: str) -> str:
# Minecraft Java offline player UUID computation: UUID.nameUUIDFromBytes(("OfflinePlayer:" + username).getBytes(UTF_8))
data = f"OfflinePlayer:{username}"
hash_digest = hashlib.md5(data.encode('utf-8')).digest()
offline_uuid = uuid.UUID(bytes=hash_digest, version=3)
return str(offline_uuid)
@classmethod
def get_user_by_username(cls, username: str) -> Optional[dict]:
conn = get_db()
cursor = conn.cursor()
cursor.execute("SELECT rowid, id, username, realname, email, regdate, password FROM authme WHERE LOWER(username) = LOWER(?)", (username,))
row = cursor.fetchone()
if not row:
conn.close()
return None
# Get role
cursor.execute("SELECT role FROM user_roles WHERE LOWER(username) = LOWER(?)", (username,))
role_row = cursor.fetchone()
role = role_row["role"] if role_row else "player"
conn.close()
user_dict = dict(row)
user_dict["role"] = role
user_dict["uuid"] = cls.calculate_offline_uuid(user_dict["realname"])
if user_dict["id"] is None:
user_dict["id"] = user_dict["rowid"]
return user_dict
@classmethod
def list_all_users(cls) -> List[dict]:
conn = get_db()
cursor = conn.cursor()
cursor.execute("SELECT rowid, id, username, realname, email, regdate FROM authme")
players = [dict(row) for row in cursor.fetchall()]
cursor.execute("SELECT username, role FROM user_roles")
roles = {row["username"].lower(): row["role"] for row in cursor.fetchall()}
conn.close()
for p in players:
p["role"] = roles.get(p["username"].lower(), "player")
p["uuid"] = cls.calculate_offline_uuid(p["realname"])
if p["id"] is None:
p["id"] = p["rowid"]
return players
@classmethod
def create_user(cls, username: str, password_raw: str, email: Optional[str] = None, role: str = "player") -> dict:
salt = AuthService.generate_salt()
authme_hash = AuthService.hash_password(password_raw, salt)
conn = get_db()
cursor = conn.cursor()
# Calculate next ID manually since it isn't autoincremented natively by SQLite in AuthMe's default schema
cursor.execute("SELECT IFNULL(MAX(id), 0) + 1 as next_id FROM authme")
next_id = cursor.fetchone()["next_id"]
try:
# Insert into authme
cursor.execute(
"""
INSERT INTO authme (id, username, realname, password, email, regdate)
VALUES (?, ?, ?, ?, ?, ?)
""",
(next_id, username.lower(), username, authme_hash, email, int(datetime.datetime.utcnow().timestamp() * 1000))
)
# Insert role
cursor.execute(
"INSERT OR REPLACE INTO user_roles (username, role) VALUES (?, ?)",
(username.lower(), role)
)
conn.commit()
except sqlite3.IntegrityError:
conn.close()
raise HTTPException(status_code=400, detail="Username already exists")
conn.close()
return {"id": next_id, "username": username.lower(), "role": role}
@staticmethod
def delete_user(username: str):
conn = get_db()
cursor = conn.cursor()
cursor.execute("DELETE FROM authme WHERE LOWER(username) = LOWER(?)", (username,))
cursor.execute("DELETE FROM user_roles WHERE LOWER(username) = LOWER(?)", (username,))
cursor.execute("DELETE FROM reset_requests WHERE LOWER(username) = LOWER(?)", (username,))
conn.commit()
conn.close()
@staticmethod
def update_password(username: str, new_password_raw: str):
salt = AuthService.generate_salt()
new_hash = AuthService.hash_password(new_password_raw, salt)
conn = get_db()
cursor = conn.cursor()
cursor.execute("UPDATE authme SET password = ? WHERE LOWER(username) = LOWER(?)", (new_hash, username))
conn.commit()
conn.close()
@staticmethod
def update_role(username: str, role: str):
conn = get_db()
cursor = conn.cursor()
cursor.execute("INSERT OR REPLACE INTO user_roles (username, role) VALUES (?, ?)", (username.lower(), role))
conn.commit()
conn.close()
class ResetRequestService:
@staticmethod
def create_request(username: str):
conn = get_db()
cursor = conn.cursor()
cursor.execute(
"INSERT OR REPLACE INTO reset_requests (username, status, requested_at) VALUES (?, 'pending', CURRENT_TIMESTAMP)",
(username.lower(),)
)
conn.commit()
conn.close()
@staticmethod
def list_requests() -> List[dict]:
conn = get_db()
cursor = conn.cursor()
cursor.execute("SELECT username, status, requested_at FROM reset_requests WHERE status = 'pending' ORDER BY requested_at DESC")
rows = [dict(row) for row in cursor.fetchall()]
conn.close()
return rows
@staticmethod
def delete_request(username: str):
conn = get_db()
cursor = conn.cursor()
cursor.execute("DELETE FROM reset_requests WHERE LOWER(username) = LOWER(?)", (username,))
conn.commit()
conn.close()
# Dependency Injection helpers
def get_current_user(cookie: Optional[str] = Depends(cookie_scheme)) -> dict:
if not cookie:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
username = AuthService.decode_jwt_token(cookie)
if not username:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid session")
user = PlayerService.get_user_by_username(username)
if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
return {"username": user["username"], "role": user["role"]}
def require_admin(current_user: dict = Depends(get_current_user)) -> dict:
if current_user["role"] != "admin":
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin permissions required")
return current_user
File diff suppressed because it is too large. Load diff