feat: implement full backend + frontend server detail, settings, and create server pages
Backend: - Complete FastAPI backend with 42+ REST endpoints (auth, servers, config, players, bans, missions, mods, games, system) - Game adapter architecture with Arma 3 as first-class adapter - WebSocket real-time events for status, metrics, logs, players - Background thread system (process monitor, metrics, log tail, RCon poller) - Fernet encryption for sensitive config fields at rest - JWT auth with admin/viewer roles, bcrypt password hashing - SQLite with WAL mode, parameterized queries, migration system - APScheduler cleanup jobs for logs, metrics, events Frontend: - Server Detail page with 7 tabs (overview, config, players, bans, missions, mods, logs) - Settings page with password change and admin user management - Create Server wizard (4-step; known bug: silent validation failure) - New hooks: useServerDetail, useAuth, useGames - New components: ServerHeader, ConfigEditor, PlayerTable, BanTable, MissionList, ModList, LogViewer, PasswordChange, UserManager - WebSocket onEvent callback for real-time log accumulation - 120 unit tests passing (Vitest + React Testing Library) Docs: - Added .gitignore, CLAUDE.md, README.md - Updated FRONTEND.md, ARCHITECTURE.md with current implementation state - Added .env.example for backend configuration Known issues: - Create Server form: "Next" buttons don't validate before advancing, causing silent submit failure when fields are invalid - Config sub-tabs need UX redesign for non-technical users
This commit is contained in:
0
backend/core/auth/__init__.py
Normal file
0
backend/core/auth/__init__.py
Normal file
77
backend/core/auth/router.py
Normal file
77
backend/core/auth/router.py
Normal file
@@ -0,0 +1,77 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from sqlalchemy.engine import Connection
|
||||
|
||||
from core.auth.schemas import (
|
||||
ChangePasswordRequest, CreateUserRequest, LoginRequest,
|
||||
)
|
||||
from core.auth.service import AuthService
|
||||
from database import get_db
|
||||
from dependencies import get_current_user, require_admin
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
# Rate limiter will be attached after main.py is imported
|
||||
_limiter = None
|
||||
|
||||
|
||||
def _ok(data):
|
||||
return {"success": True, "data": data, "error": None}
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
def login(
|
||||
request: Request,
|
||||
body: LoginRequest,
|
||||
db: Annotated[Connection, Depends(get_db)],
|
||||
):
|
||||
return _ok(AuthService(db).login(body.username, body.password))
|
||||
|
||||
|
||||
@router.post("/logout")
|
||||
def logout(user: Annotated[dict, Depends(get_current_user)]):
|
||||
# Client-side token deletion. No server-side blacklist.
|
||||
return _ok({"message": "Logged out"})
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
def me(user: Annotated[dict, Depends(get_current_user)]):
|
||||
return _ok({"id": user["id"], "username": user["username"], "role": user["role"]})
|
||||
|
||||
|
||||
@router.put("/password")
|
||||
def change_password(
|
||||
body: ChangePasswordRequest,
|
||||
user: Annotated[dict, Depends(get_current_user)],
|
||||
db: Annotated[Connection, Depends(get_db)],
|
||||
):
|
||||
AuthService(db).change_password(user["id"], body.current_password, body.new_password)
|
||||
return _ok({"message": "Password changed"})
|
||||
|
||||
|
||||
@router.get("/users")
|
||||
def list_users(
|
||||
_admin: Annotated[dict, Depends(require_admin)],
|
||||
db: Annotated[Connection, Depends(get_db)],
|
||||
):
|
||||
return _ok(AuthService(db).list_users())
|
||||
|
||||
|
||||
@router.post("/users", status_code=201)
|
||||
def create_user(
|
||||
body: CreateUserRequest,
|
||||
_admin: Annotated[dict, Depends(require_admin)],
|
||||
db: Annotated[Connection, Depends(get_db)],
|
||||
):
|
||||
user = AuthService(db).create_user(body.username, body.password, body.role)
|
||||
return _ok(user)
|
||||
|
||||
|
||||
@router.delete("/users/{user_id}", status_code=204)
|
||||
def delete_user(
|
||||
user_id: int,
|
||||
admin: Annotated[dict, Depends(require_admin)],
|
||||
db: Annotated[Connection, Depends(get_db)],
|
||||
):
|
||||
AuthService(db).delete_user(user_id, admin["id"])
|
||||
31
backend/core/auth/schemas.py
Normal file
31
backend/core/auth/schemas.py
Normal file
@@ -0,0 +1,31 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
class TokenResponse(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
expires_in: int
|
||||
user: dict
|
||||
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
id: int
|
||||
username: str
|
||||
role: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class CreateUserRequest(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
role: str = "viewer"
|
||||
|
||||
|
||||
class ChangePasswordRequest(BaseModel):
|
||||
current_password: str
|
||||
new_password: str
|
||||
105
backend/core/auth/service.py
Normal file
105
backend/core/auth/service.py
Normal file
@@ -0,0 +1,105 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.engine import Connection
|
||||
|
||||
from core.auth.utils import create_access_token, hash_password, verify_password
|
||||
from config import settings
|
||||
|
||||
|
||||
class AuthService:
|
||||
|
||||
def __init__(self, db: Connection):
|
||||
self._db = db
|
||||
|
||||
def login(self, username: str, password: str) -> dict:
|
||||
row = self._db.execute(
|
||||
text("SELECT * FROM users WHERE username = :u"), {"u": username}
|
||||
).fetchone()
|
||||
|
||||
if row is None or not verify_password(password, row.password_hash):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail={"code": "UNAUTHORIZED", "message": "Invalid credentials"},
|
||||
)
|
||||
|
||||
user = dict(row._mapping)
|
||||
self._db.execute(
|
||||
text("UPDATE users SET last_login = datetime('now') WHERE id = :id"),
|
||||
{"id": user["id"]},
|
||||
)
|
||||
|
||||
token = create_access_token(user["id"], user["username"], user["role"])
|
||||
return {
|
||||
"access_token": token,
|
||||
"token_type": "bearer",
|
||||
"expires_in": settings.jwt_expire_hours * 3600,
|
||||
"user": {"id": user["id"], "username": user["username"], "role": user["role"]},
|
||||
}
|
||||
|
||||
def create_user(self, username: str, password: str, role: str = "viewer") -> dict:
|
||||
existing = self._db.execute(
|
||||
text("SELECT id FROM users WHERE username = :u"), {"u": username}
|
||||
).fetchone()
|
||||
if existing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail={"code": "CONFLICT", "message": f"Username '{username}' already taken"},
|
||||
)
|
||||
self._db.execute(
|
||||
text(
|
||||
"INSERT INTO users (username, password_hash, role) VALUES (:u, :ph, :r)"
|
||||
),
|
||||
{"u": username, "ph": hash_password(password), "r": role},
|
||||
)
|
||||
row = self._db.execute(
|
||||
text("SELECT id, username, role, created_at FROM users WHERE username = :u"),
|
||||
{"u": username},
|
||||
).fetchone()
|
||||
return dict(row._mapping)
|
||||
|
||||
def change_password(self, user_id: int, current_password: str, new_password: str) -> None:
|
||||
row = self._db.execute(
|
||||
text("SELECT password_hash FROM users WHERE id = :id"),
|
||||
{"id": user_id},
|
||||
).fetchone()
|
||||
if row is None or not verify_password(current_password, row.password_hash):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail={"code": "UNAUTHORIZED", "message": "Current password is incorrect"},
|
||||
)
|
||||
self._db.execute(
|
||||
text("UPDATE users SET password_hash = :ph WHERE id = :id"),
|
||||
{"ph": hash_password(new_password), "id": user_id},
|
||||
)
|
||||
|
||||
def list_users(self) -> list[dict]:
|
||||
rows = self._db.execute(
|
||||
text("SELECT id, username, role, created_at, last_login FROM users ORDER BY id")
|
||||
).fetchall()
|
||||
return [dict(r._mapping) for r in rows]
|
||||
|
||||
def delete_user(self, user_id: int, requesting_user_id: int) -> None:
|
||||
if user_id == requesting_user_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail={"code": "VALIDATION_ERROR", "message": "Cannot delete yourself"},
|
||||
)
|
||||
self._db.execute(
|
||||
text("DELETE FROM users WHERE id = :id"),
|
||||
{"id": user_id},
|
||||
)
|
||||
|
||||
def seed_admin_if_empty(self) -> str | None:
|
||||
"""
|
||||
Create a default admin user if no users exist.
|
||||
Returns the generated password (printed to stdout on startup).
|
||||
"""
|
||||
count = self._db.execute(text("SELECT COUNT(*) FROM users")).fetchone()[0]
|
||||
if count > 0:
|
||||
return None
|
||||
import secrets
|
||||
password = secrets.token_urlsafe(16)
|
||||
self.create_user("admin", password, "admin")
|
||||
return password
|
||||
48
backend/core/auth/utils.py
Normal file
48
backend/core/auth/utils.py
Normal file
@@ -0,0 +1,48 @@
|
||||
"""JWT creation/validation and password hashing."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import bcrypt
|
||||
from jose import JWTError, jwt
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""Hash a password using bcrypt. Returns UTF-8 encoded hash string."""
|
||||
password_bytes = password.encode("utf-8")
|
||||
salt = bcrypt.gensalt()
|
||||
hashed = bcrypt.hashpw(password_bytes, salt)
|
||||
return hashed.decode("utf-8")
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
"""Verify a plain password against a bcrypt hash."""
|
||||
try:
|
||||
return bcrypt.checkpw(plain.encode("utf-8"), hashed.encode("utf-8"))
|
||||
except Exception as exc:
|
||||
logger.warning("Password verification failed: %s", exc)
|
||||
return False
|
||||
|
||||
|
||||
def create_access_token(user_id: int, username: str, role: str) -> str:
|
||||
from config import settings
|
||||
expire = datetime.now(timezone.utc) + timedelta(hours=settings.jwt_expire_hours)
|
||||
payload = {
|
||||
"sub": str(user_id),
|
||||
"username": username,
|
||||
"role": role,
|
||||
"exp": expire,
|
||||
}
|
||||
return jwt.encode(payload, settings.secret_key, algorithm="HS256")
|
||||
|
||||
|
||||
def decode_access_token(token: str) -> dict:
|
||||
"""
|
||||
Decode and validate JWT. Returns payload dict.
|
||||
Raises JWTError on invalid/expired token.
|
||||
"""
|
||||
from config import settings
|
||||
return jwt.decode(token, settings.secret_key, algorithms=["HS256"])
|
||||
Reference in New Issue
Block a user