2023-11-23 22:58:55 +00:00
|
|
|
from functools import wraps
|
2023-11-30 06:42:41 +00:00
|
|
|
import aiohttp
|
2023-11-28 16:04:45 +00:00
|
|
|
|
|
|
|
from orm.author import Author
|
|
|
|
from services.db import local_session
|
2023-11-23 22:58:55 +00:00
|
|
|
from settings import AUTH_URL
|
|
|
|
|
|
|
|
|
|
|
|
async def check_auth(req):
|
|
|
|
token = req.headers.get("Authorization")
|
|
|
|
headers = {"Authorization": token, "Content-Type": "application/json"} # "Bearer " + removed
|
|
|
|
print(f"[services.auth] checking auth token: {token}")
|
|
|
|
|
2023-11-26 12:13:55 +00:00
|
|
|
query_name = "session"
|
|
|
|
query_type = "query"
|
2023-11-23 22:58:55 +00:00
|
|
|
operation = "GetUserId"
|
|
|
|
|
|
|
|
gql = {
|
2023-11-26 12:13:55 +00:00
|
|
|
"query": query_type + " " + operation + " { " + query_name + " { user { id } } }",
|
2023-11-23 22:58:55 +00:00
|
|
|
"operationName": operation,
|
|
|
|
"variables": None,
|
|
|
|
}
|
|
|
|
|
2023-11-30 06:42:41 +00: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-23 22:58:55 +00:00
|
|
|
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")
|
|
|
|
is_authenticated, user_id = await check_auth(req)
|
|
|
|
if not is_authenticated:
|
|
|
|
raise Exception("You are not logged in")
|
|
|
|
else:
|
2023-11-28 20:08:22 +00:00
|
|
|
# Добавляем author_id и user_id в контекст
|
2023-11-28 16:04:45 +00:00
|
|
|
with local_session() as session:
|
|
|
|
author = session.query(Author).filter(Author.user == user_id).first()
|
|
|
|
if author:
|
|
|
|
context["author_id"] = author.id
|
|
|
|
if user_id:
|
|
|
|
context["user_id"] = user_id
|
2023-11-23 22:58:55 +00:00
|
|
|
|
|
|
|
# Если пользователь аутентифицирован, выполняем резолвер
|
|
|
|
return await f(*args, **kwargs)
|
|
|
|
|
|
|
|
return decorated_function
|