base context for wrappers updated

This commit is contained in:
2025-01-17 20:00:53 +03:00
parent 61229cb761
commit 628f6bd483
21 changed files with 404 additions and 300 deletions

View File

@@ -15,6 +15,7 @@ from ApiLibrary.common.line_number import get_line_number_for_error
from ErrorHandlers.ErrorHandlers.api_exc_handler import HTTPExceptionApi
from .base_context import BaseContext
from ApiServices.Token.token_handler import OccupantTokenObject, EmployeeTokenObject
import inspect
class AuthContext(BaseContext):
@@ -42,7 +43,12 @@ class AuthContext(BaseContext):
@property
def user_id(self) -> str:
"""Get the user's UUID from token context."""
return self.token_context.user_uu_id if self.token_context else ""
return self.token_context.user_uu_id if self.token_context else None
def as_dict(self):
if not isinstance(self.token_context, dict):
return self.token_context.model_dump()
return self.token_context
def __repr__(self) -> str:
user_type = "Employee" if self.is_employee else "Occupant"
@@ -57,7 +63,7 @@ class MiddlewareModule:
@staticmethod
def get_user_from_request(
request: Request,
) -> AuthContext:
) -> dict:
"""
Get authenticated token context from request.
@@ -74,7 +80,6 @@ class MiddlewareModule:
# Get token and validate - will raise HTTPExceptionApi if invalid
redis_token = TokenService.get_access_token_from_request(request=request)
# Get token context - will validate token and raise appropriate errors
token_context = TokenService.get_object_via_access_key(access_token=redis_token)
if not token_context:
@@ -85,7 +90,7 @@ class MiddlewareModule:
sys_msg="TokenService: Token Context couldnt retrieved from redis",
)
return AuthContext(token_context=token_context)
return token_context
@classmethod
def auth_required(cls, func: Callable) -> Callable:
@@ -116,14 +121,13 @@ class MiddlewareModule:
"""
@wraps(func)
def wrapper(request: Request, *args, **kwargs):
async def wrapper(request: Request, *args, **kwargs):
# Get and validate token context from request
auth_context = cls.get_user_from_request(request)
# Attach auth context to function
func.auth = auth_context
# Create auth context and Attach auth context to both wrapper and original function
func.auth = cls.get_user_from_request(request) # This ensures the context is available in both places
# Call the original endpoint function
if inspect.iscoroutinefunction(func):
return await func(request, *args, **kwargs)
return func(request, *args, **kwargs)
return wrapper
@@ -147,7 +151,6 @@ class RequestTimingMiddleware(BaseHTTPMiddleware):
Response: Processed response with timing headers
"""
start_time = perf_counter()
# Process the request
response = await call_next(request)

View File

@@ -6,6 +6,7 @@ from functools import wraps
from typing import Callable, Dict, Any
from .auth_middleware import MiddlewareModule
from .base_context import BaseContext
import inspect
class TokenEventHandler(BaseContext):
@@ -51,26 +52,14 @@ class TokenEventMiddleware:
authenticated_func = MiddlewareModule.auth_required(func)
@wraps(authenticated_func)
def wrapper(*args, **kwargs) -> Dict[str, Any]:
async def wrapper(*args, **kwargs) -> Dict[str, Any]:
# Create handler with context
handler = TokenEventHandler(
func=authenticated_func,
url_of_endpoint=authenticated_func.url_of_endpoint,
)
# Update event-specific context
handler.update_context(
function_code="7192c2aa-5352-4e36-98b3-dafb7d036a3d" # Keep function_code as URL
)
# Copy auth context from authenticated function
if hasattr(authenticated_func, "auth"):
handler.token_context = authenticated_func.auth.token_context
# Make handler available to the function
authenticated_func.handler = handler
function_code = "7192c2aa-5352-4e36-98b3-dafb7d036a3d" # Keep function_code as URL
# Make handler available to all functions in the chain
func.func_code = {"function_code": function_code}
# Call the authenticated function
if inspect.iscoroutinefunction(authenticated_func):
return await authenticated_func(*args, **kwargs)
return authenticated_func(*args, **kwargs)
return wrapper