inbox/services/auth.py

79 lines
2.5 KiB
Python
Raw Normal View History

2023-10-11 18:19:44 +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-11 18:31:43 +00:00
2023-10-11 18:19:44 +00:00
query_name = "getSession" if INTERNAL_AUTH_SERVER else "session"
query_type = "mutation" if INTERNAL_AUTH_SERVER else "query"
operation = "GetUserId"
headers = {
"Authorization": token,
"Content-Type": "application/json"
}
gql = {
"query": query_type + " " + operation + " { " + query_name + " { user { id } } " + " }",
"operationName": operation,
2023-10-11 18:31:43 +00:00
"variables": None
2023-10-11 18:19:44 +00:00
}
2023-10-04 17:21:04 +00:00
async with AsyncClient() as client:
2023-10-11 18:19:44 +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-12 12:28:12 +00:00
try:
user_id = (
r.get("data", {}).get(query_name, {}).get("user", {}).get("id", None)
if INTERNAL_AUTH_SERVER
else r.get("data", {}).get(query_name, {}).get("user", {}).get("id", None)
)
is_authenticated = user_id is not None
return is_authenticated, user_id
except Exception as e:
print(f"response contains no proper data: {r}")
return False, None
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