Проверять аутентификацию раньше валидации тела запроса
This commit is contained in:
+10
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user