Files
inbox/services/auth.py

54 lines
1.9 KiB
Python
Raw Normal View History

2023-10-03 17:15:17 +03:00
from functools import wraps
2023-11-30 09:49:23 +03:00
import aiohttp
2023-11-28 12:05:39 +03:00
from services.core import get_author
2023-10-14 15:59:43 +03:00
from settings import AUTH_URL
2023-10-03 17:15:17 +03:00
2023-10-03 18:29:56 +03:00
2023-10-03 17:15:17 +03:00
async def check_auth(req):
token = req.headers.get("Authorization")
2023-11-22 15:09:24 +03:00
headers = {"Authorization": token, "Content-Type": "application/json"} # "Bearer " + removed
2023-10-11 14:39:08 +03:00
print(f"[services.auth] checking auth token: {token}")
2023-10-11 21:31:43 +03:00
2023-11-28 11:33:50 +03:00
query_name = "session"
query_type = "query"
2023-10-11 21:19:44 +03:00
operation = "GetUserId"
gql = {
2023-11-30 09:49:23 +03:00
"query": query_type + " " + operation + " { " + query_name + " { user { id } } }",
2023-10-11 21:19:44 +03:00
"operationName": operation,
2023-10-14 09:38:12 +03:00
"variables": None,
2023-10-11 21:19:44 +03:00
}
2023-11-30 09:49:23 +03:00
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30.0)) as session:
async with session.post(AUTH_URL, headers=headers, json=gql) as response:
print(f"[services.auth] {AUTH_URL} response: {response.status}")
if response.status != 200:
return False, None
r = await response.json()
if r:
user_id = r.get("data", {}).get(query_name, {}).get("user", {}).get("id", None)
is_authenticated = user_id is not None
return is_authenticated, user_id
2023-11-22 15:09:24 +03:00
return False, None
2023-10-03 17:15:17 +03:00
def login_required(f):
@wraps(f)
async def decorated_function(*args, **kwargs):
info = args[1]
context = info.context
req = context.get("request")
is_authenticated, user_id = await check_auth(req)
if not is_authenticated:
raise Exception("You are not logged in")
else:
2023-11-30 09:49:23 +03:00
# Добавляем author_id и user_id в контекст
context["author_id"] = await get_author(user_id)
context["user_id"] = user_id
2023-10-03 17:15:17 +03:00
# Если пользователь аутентифицирован, выполняем резолвер
return await f(*args, **kwargs)
return decorated_function