9.3. Контекст запроса

This commit is contained in:
2026-10-12 17:01:18 +03:00
parent df6b34206d
commit 921cbdb156
2 changed files with 28 additions and 0 deletions
View File
+28
View File
@@ -0,0 +1,28 @@
from typing import Any
from app.core.jwt import decode_token
from app.db import SessionLocal
from app.models import User
def get_context_value(request: Any, data: Any = None) -> dict[str, Any]:
# создать сессию SQLAlchemy (`SessionLocal()`);
db = SessionLocal()
user = None
# извлечь заголовок `Authorization`;
authorization = request.headers.get("authorization")
if authorization and authorization.lower().startswith("bearer "):
# если токен передан и валиден – найти пользователя и положить его в контекст;
try:
payload = decode_token(authorization.split(" ", 1)[1])
sub = payload.get("sub")
if isinstance(sub, str) and sub.isdigit():
candidate = db.get(User, int(sub))
if candidate is not None and candidate.is_active:
user = candidate
except ValueError:
user = None
# вернуть словарь `{"request": ..., "db": ..., "user": ...}`.
return {"request": request, "db": db, "user": user}