inbox/services/auth.py

65 lines
2.1 KiB
Python
Raw Normal View History

2023-10-11 13:41:01 +00:00
import json
2023-10-03 14:15:17 +00:00
from functools import wraps
2023-10-05 11:46:16 +00:00
from httpx import AsyncClient, HTTPError
2023-10-03 14:15:17 +00:00
from settings import AUTH_URL
2023-10-11 11:39:08 +00:00
INTERNAL_AUTH_SERVER = "v2.discours" in AUTH_URL or "testapi.discours" in AUTH_URL
2023-10-03 15:29:56 +00:00
2023-10-03 14:15:17 +00:00
async def check_auth(req):
token = req.headers.get("Authorization")
2023-10-11 11:39:08 +00:00
print(f"[services.auth] checking auth token: {token}")
2023-10-03 14:15:17 +00:00
gql = (
{"mutation": "{ getSession { user { id } } }"}
2023-10-04 20:42:39 +00:00
if INTERNAL_AUTH_SERVER
2023-10-03 14:15:17 +00:00
else {"query": "{ session { user { id } } }"}
)
headers = {"Authorization": token, "Content-Type": "application/json"}
2023-10-04 17:21:04 +00:00
async with AsyncClient() as client:
2023-10-11 12:49:07 +00:00
response = await client.post(AUTH_URL, headers=headers, data=json.dumps(gql))
2023-10-11 13:41:01 +00:00
print(f"{response.text}")
2023-10-04 17:21:04 +00:00
if response.status_code != 200:
return False, None
r = response.json()
2023-10-06 02:30:48 +00:00
user_id = (
r.get("data", {}).get("getSession", {}).get("user", {}).get("id", None)
if INTERNAL_AUTH_SERVER
else r.get("data", {}).get("session", {}).get("user", {}).get("id", None)
)
2023-10-04 17:21:04 +00:00
is_authenticated = user_id is not None
return is_authenticated, user_id
2023-10-03 14:15:17 +00: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:
# Добавляем author_id в контекст
2023-10-04 20:52:43 +00:00
context["author_id"] = user_id
2023-10-03 14:15:17 +00:00
# Если пользователь аутентифицирован, выполняем резолвер
return await f(*args, **kwargs)
return decorated_function
def auth_request(f):
@wraps(f)
async def decorated_function(*args, **kwargs):
req = args[0]
is_authenticated, user_id = await check_auth(req)
if not is_authenticated:
2023-10-04 17:21:04 +00:00
raise HTTPError("please, login first")
2023-10-03 14:15:17 +00:00
else:
2023-10-04 20:52:43 +00:00
req["author_id"] = user_id
2023-10-03 14:15:17 +00:00
return await f(*args, **kwargs)
return decorated_function