From d20190a693132ab91bb0a83ab18ace277b7cbdfe Mon Sep 17 00:00:00 2001 From: vasyukova Date: Wed, 30 Sep 2026 23:44:17 +0300 Subject: [PATCH] =?UTF-8?q?*=20=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=D0=B0=20main.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/main.py | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/app/main.py b/src/app/main.py index ed98808a..ee9c2bdf 100644 --- a/src/app/main.py +++ b/src/app/main.py @@ -87,13 +87,20 @@ _ERROR_CODES = { } -def _error_response(status_code: int, message: str, request_id: str) -> JSONResponse: +def _unauthorized_challenge(path: str) -> str: + """Basic — только для POST /api/v1/auth/sessions; остальное — Bearer.""" + if path == "/api/v1/auth/sessions": + return 'Basic realm="messenger", charset="UTF-8"' + return 'Bearer realm="messenger"' + + +def _error_response( + status_code: int, message: str, request_id: str, path: str = "" +) -> JSONResponse: code = _ERROR_CODES.get(status_code, "internal_error") headers = {} if status_code == 401: - # Basic — только для /auth/sessions; для остальных endpoint — Bearer. - # Клиент получает корректный challenge. - headers["WWW-Authenticate"] = 'Bearer realm="messenger"' + headers["WWW-Authenticate"] = _unauthorized_challenge(path) return JSONResponse( status_code=status_code, content={"error": {"code": code, "message": message, "request_id": request_id}}, @@ -105,13 +112,13 @@ def _error_response(status_code: int, message: str, request_id: str) -> JSONResp async def http_exception_handler(request: Request, exc: StarletteHTTPException): request_id = getattr(request.state, "request_id", uuid.uuid4().hex) message = exc.detail if isinstance(exc.detail, str) else "Ошибка" - return _error_response(exc.status_code, message, request_id) + return _error_response(exc.status_code, message, request_id, request.url.path) @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): request_id = getattr(request.state, "request_id", uuid.uuid4().hex) - return _error_response(400, "Неверный запрос", request_id) + return _error_response(400, "Неверный запрос", request_id, request.url.path) @app.exception_handler(Exception) @@ -119,7 +126,7 @@ async def unhandled_exception_handler(request: Request, exc: Exception): request_id = getattr(request.state, "request_id", uuid.uuid4().hex) # Внутренние детали не раскрываем; пишем в лог без секретов logger.error("event=unhandled_exception type=%s request_id=%s", type(exc).__name__, request_id) - return _error_response(500, "Внутренняя ошибка", request_id) + return _error_response(500, "Внутренняя ошибка", request_id, request.url.path) app.include_router(health.router)