inbox/services/auth.py

75 lines
2.5 KiB
Python
Raw Normal View History

2023-10-03 14:15:17 +00:00
from functools import wraps
2023-12-17 17:13:17 +00:00
2023-11-30 06:49:23 +00:00
import aiohttp
2023-12-13 22:08:47 +00:00
from aiohttp.web import HTTPUnauthorized
2023-11-28 09:05:39 +00:00
2023-12-17 17:13:17 +00:00
from services.core import get_author
2023-10-14 12:59:43 +00:00
from settings import AUTH_URL
2023-10-03 14:15:17 +00:00
2023-10-03 15:29:56 +00:00
2023-12-13 22:08:47 +00:00
async def check_auth(req) -> (bool, int | None):
2023-10-03 14:15:17 +00:00
token = req.headers.get("Authorization")
2023-12-13 22:08:47 +00:00
if token:
# Logging the authentication token
print(f"[services.auth] checking auth token: {token}")
query_name = "validate_jwt_token"
2023-12-17 20:40:40 +00:00
opeation = "ValidateToken"
2023-12-13 22:08:47 +00:00
headers = {
"Content-Type": "application/json",
}
variables = {
"params": {
"token_type": "access_token",
2023-12-17 17:13:17 +00:00
"token": token,
2023-12-13 22:08:47 +00:00
}
}
gql = {
2023-12-17 20:40:40 +00:00
"query": f"query {opeation}($params: ValidateJWTTokenInput!) {{ {query_name}(params: $params) {{ is_valid claims }} }}",
2023-12-13 22:08:47 +00:00
"variables": variables,
2023-12-17 20:40:40 +00:00
"operationName": opeation,
2023-12-13 22:08:47 +00:00
}
2023-12-17 23:22:51 +00:00
2023-12-13 22:08:47 +00:00
try:
async with aiohttp.ClientSession() as session:
async with session.post(AUTH_URL, json=gql, headers=headers) as response:
if response.status == 200:
data = await response.json()
errors = data.get("errors")
if errors:
print(f"[services.auth] errors: {errors}")
else:
user_id = data.get("data", {}).get(query_name, {}).get("claims", {}).get("sub")
2023-12-17 23:22:51 +00:00
return bool(user_id), user_id
2023-12-13 22:08:47 +00:00
except Exception as e:
2023-12-17 23:14:02 +00:00
import traceback
traceback.print_exc()
2023-12-17 23:22:51 +00:00
print(f"[services.auth] check_auth error: {e}")
2023-12-13 22:08:47 +00:00
2023-11-22 12:09:24 +00:00
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")
2023-12-17 22:47:44 +00:00
print(req)
2023-10-03 14:15:17 +00:00
is_authenticated, user_id = await check_auth(req)
if not is_authenticated:
2023-12-13 22:08:47 +00:00
# Raising HTTPUnauthorized exception if the user is not authenticated
raise HTTPUnauthorized(text="Please, login first")
2023-10-03 14:15:17 +00:00
else:
2023-11-30 06:49:23 +00:00
# Добавляем author_id и user_id в контекст
context["author_id"] = await get_author(user_id)
context["user_id"] = user_id
2023-10-03 14:15:17 +00:00
# Если пользователь аутентифицирован, выполняем резолвер
return await f(*args, **kwargs)
return decorated_function