Проверять аутентификацию раньше валидации тела запроса
Skeleton contracts / contracts (pull_request) Canceled after 0s
Application / stack (pull_request) Canceled after 0s

This commit is contained in:
Pavel Grigorev
2026-10-30 16:50:30 +03:00
parent c8d078390c
commit cd81572950
7 changed files with 36 additions and 18 deletions
+10
View File
@@ -7,6 +7,7 @@ import uuid
from fastapi import Depends, FastAPI, Header, Query, Request, Response
from fastapi.exceptions import RequestValidationError
import psycopg
from starlette.concurrency import run_in_threadpool
from starlette.exceptions import HTTPException as StarletteHTTPException
import auth
@@ -21,6 +22,8 @@ log = logging.getLogger('messenger')
Limit = Annotated[int, Query(ge=1, le=100)]
Cursor = Annotated[Optional[str], Query(min_length=1)]
PUBLIC = {('POST', '/api/v1/users'), ('POST', '/api/v1/auth/sessions')}
state = {'ready': False}
@@ -67,6 +70,13 @@ async def handle_http_error(request: Request, exc: StarletteHTTPException):
@app.exception_handler(RequestValidationError)
async def handle_validation_error(request: Request, exc: RequestValidationError):
if request.url.path.startswith('/api/v1/') and (request.method, request.url.path) not in PUBLIC:
try:
await run_in_threadpool(auth.authenticate, request.headers.get('authorization'))
except ApiError as error:
return error_response(request, error.status, error.message, error.headers)
except (psycopg.OperationalError, psycopg.InterfaceError):
return error_response(request, 503, 'Хранилище временно недоступно')
errors = exc.errors()
where = '.'.join(str(part) for part in errors[0]['loc']) if errors else 'request'
return error_response(request, 400, 'Некорректный запрос: ' + where)