core/services/auth.py

103 lines
3.3 KiB
Python
Raw Normal View History

2024-01-23 18:59:46 +00:00
from functools import wraps
2024-01-13 08:49:12 +00:00
import logging
2023-12-13 20:39:25 +00:00
2024-01-23 18:34:51 +00:00
from aiohttp import ClientSession
2024-01-23 18:59:46 +00:00
from starlette.exceptions import HTTPException
2023-12-24 22:42:39 +00:00
from settings import AUTH_URL, AUTH_SECRET
2023-10-23 14:47:11 +00:00
2024-01-13 08:49:12 +00:00
logging.basicConfig()
logger = logging.getLogger("\t[services.auth]\t")
logger.setLevel(logging.DEBUG)
2024-01-23 19:12:22 +00:00
async def request_data(gql, headers = { "Content-Type": "application/json" }):
2024-01-10 13:29:49 +00:00
try:
2024-01-23 19:12:22 +00:00
# Asynchronous HTTP request to the authentication server
2024-01-10 13:29:49 +00:00
async with 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:
2024-01-13 08:49:12 +00:00
logger.error(f"[services.auth] errors: {errors}")
2024-01-10 13:29:49 +00:00
else:
return data
except Exception as e:
2024-01-23 19:12:22 +00:00
# Handling and logging exceptions during authentication check
2024-01-13 08:49:12 +00:00
logger.error(f"[services.auth] request_data error: {e}")
2024-01-10 13:29:49 +00:00
return None
2023-12-18 07:12:17 +00:00
async def check_auth(req) -> str | None:
2023-10-23 14:47:11 +00:00
token = req.headers.get("Authorization")
2024-01-23 19:12:22 +00:00
user_id = ""
if token:
# Logging the authentication token
logger.error(f"[services.auth] checking auth token: {token}")
query_name = "validate_jwt_token"
operation = "ValidateToken"
variables = {
"params": {
"token_type": "access_token",
"token": token,
}
}
2024-01-23 18:59:46 +00:00
2024-01-23 19:12:22 +00:00
gql = {
"query": f"query {operation}($params: ValidateJWTTokenInput!) {{ {query_name}(params: $params) {{ is_valid claims }} }}",
"variables": variables,
"operationName": operation,
}
data = await request_data(gql)
if data:
user_id = data.get("data", {}).get(query_name, {}).get("claims", {}).get("sub")
2024-01-23 18:59:46 +00:00
return user_id
2024-01-23 19:12:22 +00:00
if not user_id:
raise HTTPException(status_code=401, detail="Unauthorized")
2023-12-24 22:42:39 +00:00
2024-01-10 13:29:49 +00:00
async def add_user_role(user_id):
2024-01-13 08:49:12 +00:00
logger.info(f"[services.auth] add author role for user_id: {user_id}")
2023-12-24 22:42:39 +00:00
query_name = "_update_user"
operation = "UpdateUserRoles"
headers = {"Content-Type": "application/json", "x-authorizer-admin-secret": AUTH_SECRET}
2024-01-10 13:29:49 +00:00
variables = {"params": {"roles": "author, reader", "id": user_id}}
2023-12-24 22:42:39 +00:00
gql = {
"query": f"mutation {operation}($params: UpdateUserInput!) {{ {query_name}(params: $params) {{ id roles }} }}",
"variables": variables,
"operationName": operation,
}
2024-01-10 13:29:49 +00:00
data = await request_data(gql, headers)
if data:
user_id = data.get("data", {}).get(query_name, {}).get("id")
return user_id
2023-10-23 14:47:11 +00:00
def login_required(f):
2024-01-23 18:59:46 +00:00
@wraps(f)
2023-10-23 14:47:11 +00:00
async def decorated_function(*args, **kwargs):
info = args[1]
context = info.context
req = context.get("request")
2023-12-18 07:12:17 +00:00
user_id = await check_auth(req)
if user_id:
2024-01-10 13:29:49 +00:00
context["user_id"] = user_id.strip()
2023-10-23 14:47:11 +00:00
return await f(*args, **kwargs)
return decorated_function
2024-01-23 18:59:46 +00:00
2023-10-23 14:47:11 +00:00
def auth_request(f):
2024-01-23 18:59:46 +00:00
@wraps(f)
2023-10-23 14:47:11 +00:00
async def decorated_function(*args, **kwargs):
req = args[0]
2023-12-18 07:12:17 +00:00
user_id = await check_auth(req)
if user_id:
2024-01-10 13:29:49 +00:00
req["user_id"] = user_id.strip()
2023-10-23 14:47:11 +00:00
return await f(*args, **kwargs)
return decorated_function