Files
inbox/services/auth.py

70 lines
2.4 KiB
Python
Raw Normal View History

2023-10-03 17:15:17 +03:00
from functools import wraps
2023-12-18 10:17:50 +03:00
from aiohttp import ClientSession
from starlette.exceptions import HTTPException
2023-11-28 12:05:39 +03:00
2023-12-19 18:58:26 +03:00
from services.core import get_all_authors
2023-10-14 15:59:43 +03:00
from settings import AUTH_URL
2023-10-03 17:15:17 +03:00
2023-10-03 18:29:56 +03:00
2023-12-18 10:17:50 +03:00
async def check_auth(req) -> str | None:
2023-10-03 17:15:17 +03:00
token = req.headers.get("Authorization")
2023-12-18 10:17:50 +03:00
user_id = ""
2023-12-14 01:08:47 +03:00
if token:
# Logging the authentication token
2023-12-19 17:39:53 +03:00
# print(f"[services.auth] checking auth token: {token}")
2023-12-14 01:08:47 +03:00
query_name = "validate_jwt_token"
2023-12-18 10:17:50 +03:00
operation = "ValidateToken"
2023-12-14 01:08:47 +03:00
headers = {
"Content-Type": "application/json",
}
variables = {
"params": {
"token_type": "access_token",
2023-12-17 20:13:17 +03:00
"token": token,
2023-12-14 01:08:47 +03:00
}
}
gql = {
2023-12-18 10:17:50 +03:00
"query": f"query {operation}($params: ValidateJWTTokenInput!) {{ {query_name}(params: $params) {{ is_valid claims }} }}",
2023-12-14 01:08:47 +03:00
"variables": variables,
2023-12-18 10:17:50 +03:00
"operationName": operation,
2023-12-14 01:08:47 +03:00
}
try:
2023-12-18 10:17:50 +03:00
# Asynchronous HTTP request to the authentication server
async with ClientSession() as session:
2023-12-14 01:08:47 +03:00
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-19 17:39:53 +03:00
print(f"[services.auth] got user_id: {user_id}")
2023-12-18 10:17:50 +03:00
return user_id
2023-12-14 01:08:47 +03:00
except Exception as e:
2023-12-18 10:17:50 +03:00
# Handling and logging exceptions during authentication check
print(f"[services.auth] {e}")
2023-12-18 02:14:02 +03:00
2023-12-18 10:17:50 +03:00
if not user_id:
2023-12-18 21:32:49 +03:00
raise HTTPException(status_code=401, detail="Unauthorized")
2023-10-03 17:15:17 +03: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-18 10:17:50 +03:00
user_id = await check_auth(req)
if user_id:
context["user_id"] = user_id
2023-12-19 18:58:26 +03:00
authors_by_user, authors_by_id = get_all_authors()
2023-12-19 18:13:37 +03:00
author = authors_by_user.get(user_id)
if author and "id" in author:
context["author_id"] = author["id"]
2023-10-03 17:15:17 +03:00
return await f(*args, **kwargs)
return decorated_function