core/services/auth.py

156 lines
4.9 KiB
Python
Raw Normal View History

2024-01-25 19:41:27 +00:00
from functools import wraps
2023-12-13 20:39:25 +00:00
2024-02-19 09:49:33 +00:00
import httpx
from dogpile.cache import make_region
2024-01-23 18:59:46 +00:00
2024-02-19 08:10:12 +00:00
from settings import ADMIN_SECRET, AUTH_URL
2024-02-20 16:19:46 +00:00
from services.logger import root_logger as logger
2024-01-13 08:49:12 +00:00
2024-02-21 07:27:16 +00:00
2024-01-25 19:41:27 +00:00
async def request_data(gql, headers=None):
if headers is None:
2024-02-21 07:27:16 +00:00
headers = {"Content-Type": "application/json"}
2024-01-10 13:29:49 +00:00
try:
2024-02-19 08:10:12 +00:00
async with httpx.AsyncClient() as client:
response = await client.post(AUTH_URL, json=gql, headers=headers)
if response.status_code == 200:
data = response.json()
2024-02-21 07:27:16 +00:00
errors = data.get("errors")
2024-02-19 08:10:12 +00:00
if errors:
2024-02-21 07:27:16 +00:00
logger.error(f"HTTP Errors: {errors}")
2024-02-19 08:10:12 +00:00
else:
return data
2024-01-10 13:29:49 +00:00
except Exception as e:
2024-01-23 19:12:22 +00:00
# Handling and logging exceptions during authentication check
2024-02-21 07:27:16 +00:00
logger.error(f"request_data error: {e}")
2024-01-10 13:29:49 +00:00
return None
2024-02-19 09:40:26 +00:00
# Создание региона кэша с TTL 30 секунд
2024-02-21 07:27:16 +00:00
region = make_region().configure("dogpile.cache.memory", expiration_time=30)
2024-02-19 09:40:26 +00:00
# Функция-ключ для кэширования
def auth_cache_key(req):
2024-02-21 07:27:16 +00:00
token = req.headers.get("Authorization")
2024-02-19 09:40:26 +00:00
return f"auth_token:{token}"
2024-02-21 07:27:16 +00:00
2024-02-19 09:40:26 +00:00
# Декоратор для кэширования запроса проверки токена
def cache_auth_request(f):
@wraps(f)
async def decorated_function(*args, **kwargs):
req = args[0]
cache_key = auth_cache_key(req)
result = region.get(cache_key)
if result is None:
2024-02-21 07:27:16 +00:00
[user_id, user_roles] = await f(*args, **kwargs)
2024-02-19 11:45:55 +00:00
if user_id:
region.set(cache_key, [user_id, user_roles])
2024-02-19 09:40:26 +00:00
return result
2024-02-21 07:27:16 +00:00
2024-02-19 09:40:26 +00:00
return decorated_function
2024-02-21 07:27:16 +00:00
2024-02-19 09:40:26 +00:00
# Измененная функция проверки аутентификации с кэшированием
@cache_auth_request
2024-02-19 12:51:09 +00:00
async def check_auth(req):
2024-02-21 07:27:16 +00:00
token = req.headers.get("Authorization")
user_id = ""
2024-02-19 09:56:58 +00:00
user_roles = []
2024-02-20 15:20:57 +00:00
if token:
try:
2024-02-19 12:51:09 +00:00
# Logging the authentication token
2024-02-21 07:27:16 +00:00
logger.debug(f"{token}")
query_name = "validate_jwt_token"
operation = "ValidateToken"
2024-02-19 12:51:09 +00:00
variables = {
2024-02-21 07:27:16 +00:00
"params": {
"token_type": "access_token",
"token": token,
2024-02-19 12:51:09 +00:00
}
}
2024-02-19 09:56:58 +00:00
2024-02-19 12:51:09 +00:00
gql = {
2024-02-21 07:27:16 +00:00
"query": f"query {operation}($params: ValidateJWTTokenInput!) {{ {query_name}(params: $params) {{ is_valid claims }} }}",
"variables": variables,
"operationName": operation,
2024-01-23 19:12:22 +00:00
}
2024-02-19 12:51:09 +00:00
data = await request_data(gql)
if data:
2024-02-21 07:27:16 +00:00
user_data = data.get("data", {}).get(query_name, {}).get("claims", {})
user_id = user_data.get("sub")
user_roles = user_data.get("allowed_roles")
2024-02-20 15:20:57 +00:00
except Exception as e:
import traceback
traceback.print_exc()
logger.error(e)
2024-01-23 18:59:46 +00:00
2024-02-19 09:56:58 +00:00
# Возвращаем пустые значения, если не удалось получить user_id и user_roles
return [user_id, user_roles]
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-02-21 07:27:16 +00:00
logger.info(f"add author role for user_id: {user_id}")
query_name = "_update_user"
operation = "UpdateUserRoles"
2024-01-25 19:41:27 +00:00
headers = {
2024-02-21 07:27:16 +00:00
"Content-Type": "application/json",
"x-authorizer-admin-secret": ADMIN_SECRET,
2024-01-25 19:41:27 +00:00
}
2024-02-21 07:27:16 +00:00
variables = {"params": {"roles": "author, reader", "id": user_id}}
2023-12-24 22:42:39 +00:00
gql = {
2024-02-21 07:27:16 +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-02-21 07:27:16 +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):
2024-02-21 07:27:16 +00:00
user_id = ""
2024-02-19 12:18:25 +00:00
user_roles = []
2023-10-23 14:47:11 +00:00
info = args[1]
2024-02-19 12:18:25 +00:00
try:
2024-02-21 07:27:16 +00:00
req = info.context.get("request")
2024-02-19 12:18:25 +00:00
[user_id, user_roles] = await check_auth(req)
except Exception as e:
logger.error(f"Failed to authenticate user: {e}")
if user_id:
2024-02-21 07:27:16 +00:00
logger.info(f" got {user_id} roles: {user_roles}")
info.context["user_id"] = user_id.strip()
info.context["roles"] = user_roles
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):
2024-02-21 07:27:16 +00:00
user_id = ""
2024-02-19 12:18:25 +00:00
user_roles = []
2024-02-19 12:31:51 +00:00
req = {}
2024-02-19 12:18:25 +00:00
try:
2024-02-19 12:31:51 +00:00
req = args[0]
2024-02-19 12:18:25 +00:00
[user_id, user_roles] = await check_auth(req)
except Exception as e:
2024-02-20 14:22:55 +00:00
import traceback
traceback.print_exc()
logger.error(f"Failed to authenticate user: {args} {e}")
2023-12-18 07:12:17 +00:00
if user_id:
2024-02-21 07:27:16 +00:00
logger.info(f" got {user_id} roles: {user_roles}")
req["user_id"] = user_id.strip()
req["roles"] = user_roles
2023-10-23 14:47:11 +00:00
return await f(*args, **kwargs)
return decorated_function