This commit is contained in:
2026-02-11 23:54:42 +01:00 Unverified
commit ace6f5a022
47 changed files with 5315 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
# backend\app\core\__init__.py
+62
View File
@@ -0,0 +1,62 @@
# backend/app/core/auth.py
from datetime import datetime, timedelta, timezone
from typing import Optional
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
import jwt
from jwt.exceptions import PyJWTError
from .config import SECRET_KEY, ALGORITHM, ADMIN_USER
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/token")
oauth2_scheme_optional = OAuth2PasswordBearer(tokenUrl="auth/token", auto_error=False)
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.now(timezone.utc) + expires_delta
else:
expire = datetime.now(timezone.utc) + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
async def get_current_user(token: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username = payload.get("sub")
if username is None or username != ADMIN_USER:
raise credentials_exception
except PyJWTError:
raise credentials_exception
return username
async def get_optional_user(
token: Optional[str] = Depends(oauth2_scheme_optional),
) -> Optional[str]:
if not token:
return None
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username = payload.get("sub")
if username == ADMIN_USER:
return username
except Exception:
pass
return None
+26
View File
@@ -0,0 +1,26 @@
# backend/app/core/config.py
import os
import secrets
from pwdlib import PasswordHash
DB_PATH = os.getenv("DB_PATH", "./tournaments.db")
# Security Config
SECRET_KEY = os.getenv("SECRET_KEY", secrets.token_hex(32))
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 # 24 hours
# Admin Credentials
ADMIN_USER = os.getenv("ADMIN_USER", "admin")
ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "admin")
password_hash = PasswordHash.recommended()
ADMIN_HASH = password_hash.hash(ADMIN_PASSWORD)
def verify_password(plain_password, hashed_password):
return password_hash.verify(plain_password, hashed_password)
def get_password_hash(password):
return password_hash.hash(password)
+1
View File
@@ -0,0 +1 @@
# backend\app\core\utils.py
+40
View File
@@ -0,0 +1,40 @@
# backend/app/core/websocket_manager.py
import asyncio
from fastapi import WebSocket
class ConnectionManager:
def __init__(self):
self.active_connections: set[WebSocket] = set()
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.add(websocket)
def disconnect(self, websocket: WebSocket):
self.active_connections.discard(websocket)
async def broadcast(self, message: dict):
if not self.active_connections:
return
connections_snapshot = list(self.active_connections)
async def send_safe(ws: WebSocket):
try:
await ws.send_json(message)
except Exception:
self.disconnect(ws)
await asyncio.gather(*(send_safe(ws) for ws in connections_snapshot))
manager = ConnectionManager()
async def send_ws_update(id: str):
await asyncio.gather(
manager.broadcast({"type": "dashboard_update"}),
manager.broadcast({"type": "tournament_update", "id": id}),
)