core/services/auth.py

121 lines
4.0 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
2024-01-23 18:34:51 +00:00
import time
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
from cachetools import TTLCache
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 18:59:46 +00:00
# Define a TTLCache with a time-to-live of 1800 seconds
token_cache = TTLCache(maxsize=99999, ttl=1800)
2024-01-13 08:49:12 +00:00
2024-01-23 18:34:51 +00:00
async def request_data(gql, headers={"Content-Type": "application/json"}):
2024-01-10 13:29:49 +00:00
try:
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-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
2024-01-23 18:34:51 +00:00
async def user_id_from_token(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-10 13:29:49 +00:00
2024-01-23 18:34:51 +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:
expires_in = data.get("data", {}).get(query_name, {}).get("claims", {}).get("expires_in")
user_id = data.get("data", {}).get(query_name, {}).get("claims", {}).get("sub")
if expires_in is not None and user_id is not None:
if expires_in < 100:
# Token will expire soon, remove it from cache
token_cache.pop(token, None)
else:
expires_at = time.time() + expires_in
return user_id, expires_at
2024-01-10 13:29:49 +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")
2024-01-23 18:59:46 +00:00
# Manually manage cache using a dictionary
cached_result = token_cache.get(token)
2024-01-23 18:34:51 +00:00
if cached_result:
user_id, expires_at = cached_result
if expires_at > time.time():
2024-01-10 13:29:49 +00:00
return user_id
2024-01-23 18:59:46 +00:00
# If not in cache, fetch from user_id_from_token and update cache
result = await user_id_from_token(token)
if result:
user_id, expires_at = result
token_cache[token] = (user_id, expires_at)
if expires_at > time.time():
return user_id
2024-01-23 18:34:51 +00:00
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