Files
MABEA/backend/app/core/security.py
T
patrickandClaude Sonnet 5 446e4f912d
CI / backend-tests (push) Failing after 1s
Deployment-Setup (PostgreSQL+nginx-Installer) + Sprint-0-Fixes aus Subagenten-Reviews
Installer (deploy/):
- install_server.sh: PostgreSQL+nginx auf Debian 13, idempotente Rolle/DB-Anlage,
  pgcrypto-Extension, Speicher-Tuning für 4GB-VPS, Zugangsdaten in chmod-600-Datei
  statt stdout (postgres-expert/owasp-Review)
- nginx-Template mit Security-Headern + Rate-Limit auf /auth/login
- systemd-Unit-Template mit Sandboxing (NoNewPrivileges/ProtectSystem/PrivateTmp)

Backend-Fixes (fastapi-expert-Review):
- get_db: einheitliche commit/rollback-Konvention statt Endpunkt-Copy-Paste
- Test-Fixtures auf SQLAlchemy-2.0-Savepoint-Pattern umgestellt (join_transaction_mode),
  da get_db jetzt selbst committet
- Lifespan-Handler: Startup-Guard gegen JWT-Secret-Platzhalter, engine.dispose() beim Shutdown
- JWT-Payload ohne ungenutztes roles-Claim (Rollen kommen immer frisch aus der DB)

Zusätzlich: Subagenten-Definitionen (~/.claude/agents/) auf lauffähiges Modell fixiert.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L85hmKbvX7Cqkq47KnQhFt
2026-09-03 23:00:46 +02:00

36 lines
1.1 KiB
Python

from datetime import datetime, timedelta, timezone
import jwt
from passlib.context import CryptContext
from app.core.app_settings import settings
_pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def hash_password(password: str) -> str:
return _pwd_context.hash(password)
def verify_password(plain_password: str, password_hash: str) -> bool:
return _pwd_context.verify(plain_password, password_hash)
def create_access_token(*, subject: str) -> str:
# Bewusst KEINE Rollen im Token: get_current_user liest Rollen bei jedem Request
# frisch aus der DB (Rollenänderung wirkt sofort, kein Token-Refresh nötig).
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes)
payload = {"sub": subject, "exp": expire}
return jwt.encode(payload, settings.jwt_secret_key, algorithm=settings.jwt_algorithm)
class InvalidTokenError(Exception):
pass
def decode_access_token(token: str) -> dict:
try:
return jwt.decode(token, settings.jwt_secret_key, algorithms=[settings.jwt_algorithm])
except jwt.PyJWTError as exc:
raise InvalidTokenError(str(exc)) from exc