failed-auth-lesslog
Some checks failed
Deploy on push / deploy (push) Failing after 5s

This commit is contained in:
2025-07-25 10:10:36 +03:00
parent cb946fb30e
commit fb6ef4272d
3 changed files with 25 additions and 10 deletions

View File

@@ -180,14 +180,24 @@ async def validate_graphql_context(info: GraphQLResolveInfo) -> None:
# Если авторизации нет ни в auth, ни в scope, пробуем получить и проверить токен
token = get_auth_token(request)
if not token:
# Если токен не найден, бросаем ошибку авторизации
# Если токен не найден, логируем как предупреждение, но не бросаем GraphQLError
client_info = {
"ip": getattr(request.client, "host", "unknown") if hasattr(request, "client") else "unknown",
"headers": {k: v for k, v in get_safe_headers(request).items() if k not in ["authorization", "cookie"]},
}
logger.warning(f"[validate_graphql_context] Токен авторизации не найден: {client_info}")
msg = "Unauthorized - please login"
raise GraphQLError(msg)
logger.info(f"[validate_graphql_context] Токен авторизации не найден: {client_info}")
# Устанавливаем пустые учетные данные вместо выброса исключения
if hasattr(request, "scope") and isinstance(request.scope, dict):
request.scope["auth"] = AuthCredentials(
author_id=None,
scopes={},
logged_in=False,
error_message="No authentication token",
email=None,
token=None,
)
return
# Логируем информацию о найденном токене
logger.debug(f"[validate_graphql_context] Токен найден, длина: {len(token)}")

View File

@@ -119,8 +119,8 @@ async def authenticate(request) -> AuthState:
# Получаем токен из запроса
token = get_auth_token(request)
if not token:
logger.warning("[authenticate] Токен не найден в запросе")
auth_state.error = "No authentication token provided"
logger.info("[authenticate] Токен не найден в запросе")
auth_state.error = "No authentication token"
return auth_state
logger.debug(f"[authenticate] Токен найден, длина: {len(token)}")

13
main.py
View File

@@ -6,6 +6,7 @@ from pathlib import Path
from ariadne import load_schema_from_path, make_executable_schema
from ariadne.asgi import GraphQL
from ariadne.graphql_core.error import GraphQLError
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
@@ -96,13 +97,17 @@ async def graphql_handler(request: Request) -> Response:
return await auth_middleware.process_result(request, result)
except asyncio.CancelledError:
return JSONResponse({"error": "Request cancelled"}, status_code=499)
except GraphQLError as e:
# Для GraphQL ошибок (например, неавторизованный доступ) не логируем полный трейс
logger.warning(f"GraphQL error: {e}")
return JSONResponse({"error": str(e)}, status_code=403)
except Exception as e:
logger.error(f"GraphQL error: {e!s}")
# Логируем более подробную информацию для отладки
logger.error(f"Unexpected GraphQL error: {e!s}")
# Логируем более подробную информацию для отладки только для неожиданных ошибок
import traceback
logger.debug(f"GraphQL error traceback: {traceback.format_exc()}")
return JSONResponse({"error": str(e)}, status_code=500)
logger.debug(f"Unexpected GraphQL error traceback: {traceback.format_exc()}")
return JSONResponse({"error": "Internal server error"}, status_code=500)
async def spa_handler(request: Request) -> Response: