inbox/services/auth.py

58 lines
1.8 KiB
Python
Raw Normal View History

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-04 20:42:39 +00:00
INTERNAL_AUTH_SERVER = "v2.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")
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:
response = await client.post(AUTH_URL, headers=headers, data=gql)
if response.status_code != 200:
return False, None
r = response.json()
user_id = r.get("data", {}).get("session", {}).get("user", {}).get("id", None)
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