This commit is contained in:
parent
a0f75c0505
commit
32bc750071
130
services/auth.py
130
services/auth.py
|
@ -1,7 +1,7 @@
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
from dogpile.cache import make_region
|
|
||||||
|
from starlette.exceptions import HTTPException
|
||||||
|
|
||||||
from settings import ADMIN_SECRET, AUTH_URL
|
from settings import ADMIN_SECRET, AUTH_URL
|
||||||
from services.logger import root_logger as logger
|
from services.logger import root_logger as logger
|
||||||
|
@ -22,81 +22,45 @@ async def request_data(gql, headers=None):
|
||||||
return data
|
return data
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# Handling and logging exceptions during authentication check
|
# Handling and logging exceptions during authentication check
|
||||||
logger.error(f'request_data error: {e}')
|
logger.error(f'[services.auth] request_data error: {e}')
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
# Создание региона кэша с TTL 30 секунд
|
|
||||||
region = make_region().configure('dogpile.cache.memory', expiration_time=30)
|
|
||||||
|
|
||||||
|
|
||||||
# Функция-ключ для кэширования
|
|
||||||
def auth_cache_key(req):
|
|
||||||
token = req.headers.get('Authorization')
|
|
||||||
return f'auth_token:{token}'
|
|
||||||
|
|
||||||
|
|
||||||
# Декоратор для кэширования запроса проверки токена
|
|
||||||
def cache_auth_request(f):
|
|
||||||
@wraps(f)
|
|
||||||
async def decorated_function(*args, **kwargs):
|
|
||||||
try:
|
|
||||||
req = args[0]
|
|
||||||
cache_key = auth_cache_key(req)
|
|
||||||
result = region.get(cache_key)
|
|
||||||
if result is not None: # Проверка наличия значения в кэше
|
|
||||||
logger.debug(f'CACHE found {cache_key}: {result}')
|
|
||||||
if isinstance(result, list) and len(result) == 2: # Проверка формата значения
|
|
||||||
return result
|
|
||||||
[user_id, user_roles] = await f(*args, **kwargs)
|
|
||||||
if user_id:
|
|
||||||
region.set(cache_key, [user_id, user_roles])
|
|
||||||
return [user_id, user_roles]
|
|
||||||
except Exception as e:
|
|
||||||
import traceback
|
|
||||||
logger.error(e)
|
|
||||||
traceback.print_exc()
|
|
||||||
return None
|
|
||||||
return decorated_function
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# Измененная функция проверки аутентификации с кэшированием
|
|
||||||
@cache_auth_request
|
|
||||||
async def check_auth(req):
|
async def check_auth(req):
|
||||||
token = req.headers.get('Authorization')
|
token = req.headers.get('Authorization')
|
||||||
user_id = ''
|
user_id = ''
|
||||||
user_roles = []
|
|
||||||
if token:
|
if token:
|
||||||
try:
|
# Logging the authentication token
|
||||||
# Logging the authentication token
|
logger.debug(f'{token}')
|
||||||
logger.debug(f'{token}')
|
query_name = 'validate_jwt_token'
|
||||||
query_name = 'validate_jwt_token'
|
operation = 'ValidateToken'
|
||||||
operation = 'ValidateToken'
|
variables = {
|
||||||
variables = {'params': {'token_type': 'access_token', 'token': token}}
|
'params': {
|
||||||
|
'token_type': 'access_token',
|
||||||
gql = {
|
'token': token,
|
||||||
'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_data = data.get('data', {}).get(query_name, {}).get('claims', {})
|
|
||||||
user_id = user_data.get('sub')
|
|
||||||
user_roles = user_data.get('allowed_roles')
|
|
||||||
except Exception as e:
|
|
||||||
import traceback
|
|
||||||
|
|
||||||
traceback.print_exc()
|
gql = {
|
||||||
logger.error(e)
|
'query': f'query {operation}($params: ValidateJWTTokenInput!) {{'
|
||||||
|
+ f'{query_name}(params: $params) {{ is_valid claims }} '
|
||||||
|
+ '}',
|
||||||
|
'variables': variables,
|
||||||
|
'operationName': operation,
|
||||||
|
}
|
||||||
|
data = await request_data(gql)
|
||||||
|
if data:
|
||||||
|
user_data = data.get('data', {}).get(query_name, {}).get('claims', {})
|
||||||
|
user_id = user_data.get('sub')
|
||||||
|
user_roles = user_data.get('allowed_roles')
|
||||||
|
return [user_id, user_roles]
|
||||||
|
|
||||||
# Возвращаем пустые значения, если не удалось получить user_id и user_roles
|
if not user_id:
|
||||||
return [user_id, user_roles]
|
raise HTTPException(status_code=401, detail='Unauthorized')
|
||||||
|
|
||||||
|
|
||||||
async def add_user_role(user_id):
|
async def add_user_role(user_id):
|
||||||
logger.info(f'add author role for user_id: {user_id}')
|
logger.info(f'[services.auth] add author role for user_id: {user_id}')
|
||||||
query_name = '_update_user'
|
query_name = '_update_user'
|
||||||
operation = 'UpdateUserRoles'
|
operation = 'UpdateUserRoles'
|
||||||
headers = {
|
headers = {
|
||||||
|
@ -118,22 +82,14 @@ async def add_user_role(user_id):
|
||||||
def login_required(f):
|
def login_required(f):
|
||||||
@wraps(f)
|
@wraps(f)
|
||||||
async def decorated_function(*args, **kwargs):
|
async def decorated_function(*args, **kwargs):
|
||||||
user_id = ''
|
|
||||||
user_roles = []
|
|
||||||
info = args[1]
|
info = args[1]
|
||||||
|
context = info.context
|
||||||
try:
|
req = context.get('request')
|
||||||
req = info.context.get('request')
|
[user_id, user_roles] = (await check_auth(req)) or []
|
||||||
checked_result = await check_auth(req)
|
if user_id and user_roles:
|
||||||
logger.debug(checked_result)
|
|
||||||
if checked_result and len(checked_result) > 1:
|
|
||||||
[user_id, user_roles] = checked_result
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f'Failed to authenticate user: {e}')
|
|
||||||
if user_id:
|
|
||||||
logger.info(f' got {user_id} roles: {user_roles}')
|
logger.info(f' got {user_id} roles: {user_roles}')
|
||||||
info.context['user_id'] = user_id.strip()
|
context['user_id'] = user_id.strip()
|
||||||
info.context['roles'] = user_roles
|
context['roles'] = user_roles
|
||||||
return await f(*args, **kwargs)
|
return await f(*args, **kwargs)
|
||||||
|
|
||||||
return decorated_function
|
return decorated_function
|
||||||
|
@ -142,21 +98,11 @@ def login_required(f):
|
||||||
def auth_request(f):
|
def auth_request(f):
|
||||||
@wraps(f)
|
@wraps(f)
|
||||||
async def decorated_function(*args, **kwargs):
|
async def decorated_function(*args, **kwargs):
|
||||||
user_id = ''
|
req = args[0]
|
||||||
user_roles = []
|
[user_id, user_roles] = (await check_auth(req)) or []
|
||||||
req = {}
|
|
||||||
try:
|
|
||||||
req = args[0]
|
|
||||||
[user_id, user_roles] = await check_auth(req)
|
|
||||||
except Exception as e:
|
|
||||||
import traceback
|
|
||||||
|
|
||||||
traceback.print_exc()
|
|
||||||
logger.error(f'Failed to authenticate user: {args} {e}')
|
|
||||||
if user_id:
|
if user_id:
|
||||||
logger.info(f' got {user_id} roles: {user_roles}')
|
req['user_id'] = user_id.strip()
|
||||||
req['user_id'] = user_id.strip()
|
req['roles'] = user_roles
|
||||||
req['roles'] = user_roles
|
|
||||||
return await f(*args, **kwargs)
|
return await f(*args, **kwargs)
|
||||||
|
|
||||||
return decorated_function
|
return decorated_function
|
||||||
|
|
Loading…
Reference in New Issue
Block a user