""" Wrapper pentru AuthenticationMiddleware cu fix pentru endpoint-urile protejate """ from fastapi import Request, status from fastapi.responses import JSONResponse from starlette.middleware.base import BaseHTTPMiddleware import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), '../../../shared')) from auth.middleware import AuthenticationMiddleware from auth.models import AuthError class FixedAuthenticationMiddleware(BaseHTTPMiddleware): """ Wrapper pentru AuthenticationMiddleware care aplică fix-ul pentru endpoint-urile protejate """ def __init__(self, app, **kwargs): super().__init__(app) # Create the original middleware instance without wrapping in BaseHTTPMiddleware self.auth_middleware = AuthenticationMiddleware(app, **kwargs) print("[FIXED MIDDLEWARE] FixedAuthenticationMiddleware initialized") print(f"[FIXED MIDDLEWARE] Original middleware type: {type(self.auth_middleware)}") async def dispatch(self, request: Request, call_next): """ Aplică fix-ul pentru endpoint-urile protejate: - Returnează 401 pentru căile protejate fără token în loc să seteze request.state """ path = request.url.path print(f"[FIXED MIDDLEWARE] Processing path: {path}") # Verifică dacă path-ul trebuie exclus excluded_paths = [ "/docs", "/health", "/api/auth/login", "/redoc", "/openapi.json", "/api/telegram/health", "/api/telegram/auth/verify-user", "/api/telegram/auth/verify-email", "/api/telegram/auth/login-with-email", "/api/telegram/auth/refresh-token" ] is_excluded = (path == "/" or any(path.startswith(excluded) for excluded in excluded_paths)) print(f"[FIXED MIDDLEWARE] Checking exclusions for {path}") print(f"[FIXED MIDDLEWARE] Excluded paths: {excluded_paths}") print(f"[FIXED MIDDLEWARE] Is excluded: {is_excluded}") if is_excluded: print(f"[FIXED MIDDLEWARE] Path {path} is excluded, skipping auth") request.state.user = None request.state.is_authenticated = False response = await call_next(request) return response # Extrage token-ul authorization = request.headers.get("Authorization") print(f"[FIXED MIDDLEWARE] Authorization header: {authorization}") if not authorization or not authorization.startswith("Bearer "): print(f"[FIXED MIDDLEWARE] No valid token for protected path {path}, returning 401") error = AuthError( error="authentication_required", error_description="Authentication required", error_code="AUTH_003" ) return JSONResponse( status_code=status.HTTP_401_UNAUTHORIZED, content=error.dict(), headers={"WWW-Authenticate": "Bearer"} ) # Token există, să îl validez prin middleware-ul original print(f"[FIXED MIDDLEWARE] Token found, delegating to original middleware") try: result = await self.auth_middleware.dispatch(request, call_next) print(f"[FIXED MIDDLEWARE] Original middleware returned: {type(result)}") print(f"[FIXED MIDDLEWARE] Request state after middleware: user={getattr(request.state, 'user', 'MISSING')}, is_authenticated={getattr(request.state, 'is_authenticated', 'MISSING')}") return result except Exception as e: print(f"[FIXED MIDDLEWARE] Exception in original middleware: {str(e)}") raise