core/services/auth.py

103 lines
3.6 KiB
Python
Raw Normal View History

2023-10-23 14:47:11 +00:00
from functools import wraps
2023-12-17 20:30:20 +00:00
2023-12-18 15:37:39 +00:00
from aiohttp import ClientSession
from starlette.exceptions import HTTPException
2023-12-13 20:39:25 +00:00
2023-12-24 22:42:39 +00:00
from settings import AUTH_URL, AUTH_SECRET
2023-10-23 14:47:11 +00:00
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")
2023-12-18 07:12:17 +00:00
user_id = ""
2023-12-12 05:00:46 +00:00
if token:
2023-12-13 20:39:25 +00:00
# Logging the authentication token
2023-12-12 05:00:46 +00:00
print(f"[services.auth] checking auth token: {token}")
2023-12-13 20:39:25 +00:00
query_name = "validate_jwt_token"
2023-12-18 07:12:17 +00:00
operation = "ValidateToken"
2023-12-13 20:39:25 +00:00
headers = {
"Content-Type": "application/json",
}
variables = {
"params": {
"token_type": "access_token",
2023-12-14 00:06:35 +00:00
"token": token,
2023-12-13 20:39:25 +00:00
}
}
2023-12-11 19:12:18 +00:00
2023-12-12 05:00:46 +00:00
gql = {
2023-12-18 07:12:17 +00:00
"query": f"query {operation}($params: ValidateJWTTokenInput!) {{ {query_name}(params: $params) {{ is_valid claims }} }}",
2023-12-13 20:39:25 +00:00
"variables": variables,
2023-12-18 07:12:17 +00:00
"operationName": operation,
2023-12-12 05:00:46 +00:00
}
2023-12-13 20:39:25 +00:00
try:
# Asynchronous HTTP request to the authentication server
2023-12-18 15:37:39 +00:00
async with ClientSession() as session:
2023-12-13 20:39:25 +00:00
async with session.post(AUTH_URL, json=gql, headers=headers) as response:
if response.status == 200:
data = await response.json()
2023-12-13 20:54:38 +00:00
errors = data.get("errors")
if errors:
2023-12-13 21:17:20 +00:00
print(f"[services.auth] errors: {errors}")
2023-12-13 20:39:25 +00:00
else:
2023-12-13 20:54:38 +00:00
user_id = data.get("data", {}).get(query_name, {}).get("claims", {}).get("sub")
2023-12-18 07:12:17 +00:00
return user_id
2023-12-13 20:39:25 +00:00
except Exception as e:
# Handling and logging exceptions during authentication check
2023-12-13 21:17:20 +00:00
print(f"[services.auth] {e}")
2023-12-13 20:39:25 +00:00
2023-12-18 07:12:17 +00:00
if not user_id:
2023-12-24 22:42:39 +00:00
raise HTTPException(status_code=401, detail="Unauthorized")
async def add_author_role(author_id):
print(f"[services.auth] add author role for author with id {author_id}")
query_name = "_update_user"
operation = "UpdateUserRoles"
headers = {"Content-Type": "application/json", "x-authorizer-admin-secret": AUTH_SECRET}
variables = {"params": {"roles": "author, reader"}}
gql = {
"query": f"mutation {operation}($params: UpdateUserInput!) {{ {query_name}(params: $params) {{ id roles }} }}",
"variables": variables,
"operationName": operation,
}
try:
# Asynchronous HTTP request to the authentication server
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:
print(f"[services.auth] errors: {errors}")
else:
user_id = data.get("data", {}).get(query_name, {}).get("id")
return user_id
except Exception as e:
print(f"[services.auth] {e}")
2023-10-23 14:47:11 +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-18 07:12:17 +00:00
user_id = await check_auth(req)
if user_id:
2023-12-13 20:42:19 +00:00
context["user_id"] = user_id
2023-10-23 14:47:11 +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]
2023-12-18 07:12:17 +00:00
user_id = await check_auth(req)
if user_id:
2023-12-13 20:42:19 +00:00
req["user_id"] = user_id
2023-10-23 14:47:11 +00:00
return await f(*args, **kwargs)
return decorated_function