77 lines
2.4 KiB
Python
77 lines
2.4 KiB
Python
"""
|
|
Token event middleware for handling authentication and event tracking.
|
|
"""
|
|
|
|
from functools import wraps
|
|
from typing import Callable, Dict, Any
|
|
from .auth_middleware import MiddlewareModule
|
|
from .base_context import BaseContext
|
|
|
|
|
|
class TokenEventHandler(BaseContext):
|
|
"""Handler for token events with authentication context."""
|
|
|
|
def __init__(self, func: Callable, url_of_endpoint: str):
|
|
"""Initialize the handler with function and URL."""
|
|
super().__init__()
|
|
self.func = func
|
|
self.url_of_endpoint = url_of_endpoint
|
|
|
|
def update_context(self, function_code: str):
|
|
"""Update the event context with function code."""
|
|
self.function_code = function_code
|
|
|
|
|
|
class TokenEventMiddleware:
|
|
"""
|
|
Module containing token and event handling functionality.
|
|
|
|
This class provides:
|
|
- Token and event context management
|
|
- Event validation decorator for endpoints
|
|
"""
|
|
|
|
@staticmethod
|
|
def event_required(
|
|
func: Callable[..., Dict[str, Any]]
|
|
) -> Callable[..., Dict[str, Any]]:
|
|
"""
|
|
Decorator for endpoints with token and event requirements.
|
|
This decorator:
|
|
1. First validates authentication using MiddlewareModule.auth_required
|
|
2. Then adds event tracking context
|
|
|
|
Args:
|
|
func: The function to be decorated
|
|
|
|
Returns:
|
|
Callable: The wrapped function with both auth and event handling
|
|
"""
|
|
# First apply authentication
|
|
authenticated_func = MiddlewareModule.auth_required(func)
|
|
|
|
@wraps(authenticated_func)
|
|
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
|
|
|
|
# Call the authenticated function
|
|
return authenticated_func(*args, **kwargs)
|
|
|
|
return wrapper
|