diff --git a/app/graphql/__init__.py b/app/graphql/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/graphql/context.py b/app/graphql/context.py new file mode 100644 index 0000000..3ccf352 --- /dev/null +++ b/app/graphql/context.py @@ -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}