core/services/auth.py

110 lines
3.4 KiB
Python
Raw Normal View History

2024-01-13 08:49:12 +00:00
import logging
2024-01-25 19:41:27 +00:00
from functools import wraps
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
2024-01-25 19:41:27 +00:00
from settings import AUTH_SECRET, AUTH_URL
2023-10-23 14:47:11 +00:00
2024-01-13 08:49:12 +00:00
logging.basicConfig()
2024-01-25 19:41:27 +00:00
logger = logging.getLogger('\t[services.auth]\t')
2024-01-13 08:49:12 +00:00
logger.setLevel(logging.DEBUG)
2024-01-25 19:41:27 +00:00
async def request_data(gql, headers=None):
if headers is None:
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()
2024-01-25 19:41:27 +00:00
errors = data.get('errors')
2024-01-10 13:29:49 +00:00
if errors:
2024-01-25 19:41:27 +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-25 19:41:27 +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:
2024-01-25 19:41:27 +00:00
token = req.headers.get('Authorization')
user_id = ''
2024-01-23 19:12:22 +00:00
if token:
# Logging the authentication token
2024-01-25 19:41:27 +00:00
logger.error(f'[services.auth] checking auth token: {token}')
query_name = 'validate_jwt_token'
operation = 'ValidateToken'
2024-01-23 19:12:22 +00:00
variables = {
2024-01-25 19:41:27 +00:00
'params': {
'token_type': 'access_token',
'token': token,
2024-01-23 19:12:22 +00:00
}
}
2024-01-23 18:59:46 +00:00
2024-01-23 19:12:22 +00:00
gql = {
2024-01-29 10:02:14 +00:00
'query': f'query {operation}($params: ValidateJWTTokenInput!) {{' +
f'{query_name}(params: $params) {{ is_valid claims }} ' +
'}',
2024-01-25 19:41:27 +00:00
'variables': variables,
'operationName': operation,
2024-01-23 19:12:22 +00:00
}
data = await request_data(gql)
if data:
2024-01-25 19:41:27 +00:00
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:
2024-01-25 19:41:27 +00:00
raise HTTPException(status_code=401, detail='Unauthorized')
2024-01-23 19:12:22 +00:00
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-25 19:41:27 +00:00
logger.info(f'[services.auth] add author role for user_id: {user_id}')
query_name = '_update_user'
operation = 'UpdateUserRoles'
headers = {
'Content-Type': 'application/json',
'x-authorizer-admin-secret': AUTH_SECRET,
}
variables = {'params': {'roles': 'author, reader', 'id': user_id}}
2023-12-24 22:42:39 +00:00
gql = {
2024-01-25 19:41:27 +00:00
'query': f'mutation {operation}($params: UpdateUserInput!) {{ {query_name}(params: $params) {{ id roles }} }}',
'variables': variables,
'operationName': operation,
2023-12-24 22:42:39 +00:00
}
2024-01-10 13:29:49 +00:00
data = await request_data(gql, headers)
if data:
2024-01-25 19:41:27 +00:00
user_id = data.get('data', {}).get(query_name, {}).get('id')
2024-01-10 13:29:49 +00:00
return user_id
2023-10-23 14:47:11 +00:00
2024-01-25 19:41:27 +00:00
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
2024-01-25 19:41:27 +00:00
req = context.get('request')
2023-12-18 07:12:17 +00:00
user_id = await check_auth(req)
if user_id:
2024-01-25 19:41:27 +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-25 19:41:27 +00:00
req['user_id'] = user_id.strip()
2023-10-23 14:47:11 +00:00
return await f(*args, **kwargs)
return decorated_function