from functools import wraps import aiohttp from aiohttp.web import HTTPUnauthorized from services.core import get_author from settings import AUTH_URL async def check_auth(req) -> (bool, int | None): token = req.headers.get("Authorization") if token: # Logging the authentication token print(f"[services.auth] checking auth token: {token}") query_name = "validate_jwt_token" opeation = "ValidateToken" headers = { "Content-Type": "application/json", } variables = { "params": { "token_type": "access_token", "token": token, } } gql = { "query": f"query {opeation}($params: ValidateJWTTokenInput!) {{ {query_name}(params: $params) {{ is_valid claims }} }}", "variables": variables, "operationName": opeation, } try: async with aiohttp.ClientSession() as session: async with session.post(AUTH_URL, json=gql, headers=headers) as response: if response.status == 200: data = await response.json() errors = data.get("errors") if errors: print(f"[services.auth] errors: {errors}") else: user_id = data.get("data", {}).get(query_name, {}).get("claims", {}).get("sub") return bool(user_id), user_id except Exception as e: import traceback traceback.print_exc() print(f"[services.auth] check_auth error: {e}") return False, None def login_required(f): @wraps(f) async def decorated_function(*args, **kwargs): info = args[1] context = info.context req = context.get("request") print(req) is_authenticated, user_id = await check_auth(req) if not is_authenticated: # Raising HTTPUnauthorized exception if the user is not authenticated raise HTTPUnauthorized(text="Please, login first") else: # Добавляем author_id и user_id в контекст context["author_id"] = await get_author(user_id) context["user_id"] = user_id # Если пользователь аутентифицирован, выполняем резолвер return await f(*args, **kwargs) return decorated_function