error response due to language models are updated

This commit is contained in:
2025-01-15 13:39:17 +03:00
parent ad0b9aa218
commit 25539c56cc
17 changed files with 163 additions and 208 deletions

View File

@@ -8,7 +8,7 @@ and a middleware for request timing measurements.
from time import perf_counter
from typing import Callable, Optional, Dict, Any, Tuple
from functools import wraps
from fastapi import HTTPException, Request, Response, status
from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware
from AllConfigs.Token.config import Auth
from ErrorHandlers.ErrorHandlers.api_exc_handler import HTTPExceptionApi
@@ -21,7 +21,6 @@ class MiddlewareModule:
This class provides:
- Token extraction and validation
- Authentication decorator for endpoints
- Request timing middleware
"""
@staticmethod
@@ -40,23 +39,15 @@ class MiddlewareModule:
"""
auth_header = request.headers.get(Auth.ACCESS_TOKEN_TAG)
if not auth_header:
raise HTTPExceptionApi(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="No authorization header",
)
raise HTTPExceptionApi(error_code="HTTP_401_UNAUTHORIZED", lang="tr")
try:
scheme, token = auth_header.split()
if scheme.lower() != "bearer":
raise HTTPExceptionApi(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication scheme",
)
raise HTTPExceptionApi(error_code="HTTP_401_UNAUTHORIZED", lang="tr")
return scheme, token
except ValueError:
raise HTTPExceptionApi(
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token format"
)
raise HTTPExceptionApi(error_code="HTTP_401_UNAUTHORIZED", lang="tr")
@staticmethod
async def validate_token(token: str) -> Dict[str, Any]:
@@ -78,10 +69,7 @@ class MiddlewareModule:
# return jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
return {"user_id": "test", "role": "user"} # Placeholder
except Exception as e:
raise HTTPExceptionApi(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=f"Token validation failed: {str(e)}",
)
raise HTTPExceptionApi(error_code="HTTP_401_UNAUTHORIZED", lang="tr")
@classmethod
def auth_required(cls, func: Callable) -> Callable:
@@ -122,58 +110,44 @@ class MiddlewareModule:
return await func(request, *args, **kwargs)
except HTTPExceptionApi:
raise
raise HTTPExceptionApi(error_code="NOT_AUTHORIZED", lang="tr")
except Exception as e:
raise HTTPExceptionApi(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=f"Authentication failed: {str(e)}",
)
raise HTTPExceptionApi(error_code="NOT_AUTHORIZED", lang="tr")
return wrapper
class RequestTimingMiddleware(BaseHTTPMiddleware):
class RequestTimingMiddleware(BaseHTTPMiddleware):
"""
Middleware for measuring and logging request timing.
Only handles timing, no authentication.
"""
async def dispatch(self, request: Request, call_next: Callable) -> Response:
"""
Middleware for measuring and logging request timing.
Only handles timing, no authentication.
Process each request through the middleware.
Args:
request: FastAPI request object
call_next: Next middleware in the chain
Returns:
Response: Processed response with timing headers
"""
start_time = perf_counter()
async def dispatch(self, request: Request, call_next: Callable) -> Response:
"""
Process each request through the middleware.
# Process the request
response = await call_next(request)
Args:
request: FastAPI request object
call_next: Next middleware in the chain
# Add timing information to response headers
end_time = perf_counter()
elapsed = (end_time - start_time) * 1000 # Convert to milliseconds
Returns:
Response: Processed response with timing headers
"""
start_time = perf_counter()
response.headers.update(
{
"request-start": f"{start_time:.6f}",
"request-end": f"{end_time:.6f}",
"request-duration": f"{elapsed:.2f}ms",
}
)
# Process the request
response = await call_next(request)
# Add timing information to response headers
self._add_timing_headers(response, start_time)
return response
@staticmethod
def _add_timing_headers(response: Response, start_time: float) -> None:
"""
Add request timing information to response headers.
Args:
response: FastAPI response object
start_time: Time when request processing started
"""
end_time = perf_counter()
elapsed = (end_time - start_time) * 1000 # Convert to milliseconds
response.headers.update(
{
"request-start": f"{start_time:.6f}",
"request-end": f"{end_time:.6f}",
"request-duration": f"{elapsed:.2f}ms",
}
)
return response