Spaces:
Paused
Paused
Download shared/middleware.py from VAH6002/ai_data_scientist: direct link, hf CLI and curl.
- Browser
- Download file 5.22 kB
-
https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/shared/middleware.py
- Command line
-
hf download hf://spaces/VAH6002/ai_data_scientist/shared/middleware.py
-
curl -L -o middleware.py https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/shared/middleware.py
5.22 kB
| """ | |
| FastAPI middleware for Clerk authentication integration. | |
| Handles JWT token extraction, validation, and user context injection. | |
| """ | |
| from typing import Optional, Callable, Awaitable | |
| from fastapi import Request, Response, HTTPException, status | |
| from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials | |
| from starlette.middleware.base import BaseHTTPMiddleware | |
| from starlette.responses import JSONResponse | |
| import logging | |
| from shared.auth import jwt_validator, UserContext | |
| logger = logging.getLogger(__name__) | |
| class AuthenticationMiddleware(BaseHTTPMiddleware): | |
| """Middleware to handle Clerk JWT authentication for all requests.""" | |
| def __init__(self, app, exclude_paths: Optional[list] = None): | |
| super().__init__(app) | |
| # Paths that don't require authentication | |
| self.exclude_paths = exclude_paths or [ | |
| "/health", | |
| "/docs", | |
| "/redoc", | |
| "/openapi.json", | |
| "/favicon.ico" | |
| ] | |
| async def dispatch(self, request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response: | |
| """Process request and inject user context if authenticated.""" | |
| # Skip authentication for excluded paths | |
| if any(request.url.path.startswith(path) for path in self.exclude_paths): | |
| return await call_next(request) | |
| # Extract token from Authorization header | |
| token = self._extract_token(request) | |
| if token: | |
| try: | |
| # Validate token and get user context | |
| user_context = await jwt_validator.validate_token(token) | |
| # Inject user context into request state | |
| request.state.user = user_context | |
| logger.info(f"Authenticated user: {user_context.user_id}") | |
| except HTTPException as e: | |
| # Return authentication error | |
| return JSONResponse( | |
| status_code=e.status_code, | |
| content={"detail": e.detail} | |
| ) | |
| except Exception as e: | |
| logger.error(f"Authentication error: {str(e)}") | |
| return JSONResponse( | |
| status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | |
| content={"detail": "Authentication service error"} | |
| ) | |
| else: | |
| # No token provided - set anonymous user context | |
| request.state.user = UserContext( | |
| user_id="anonymous", | |
| clerk_user_id="anonymous", | |
| is_authenticated=False | |
| ) | |
| # Continue with request processing | |
| response = await call_next(request) | |
| return response | |
| def _extract_token(self, request: Request) -> Optional[str]: | |
| """Extract JWT token from Authorization header.""" | |
| authorization = request.headers.get("Authorization") | |
| if not authorization: | |
| return None | |
| # Handle Bearer token format | |
| if authorization.startswith("Bearer "): | |
| return authorization[7:] # Remove "Bearer " prefix | |
| return None | |
| class RequireAuth: | |
| """Dependency to require authentication for specific endpoints.""" | |
| def __init__(self, required_permission: Optional[str] = None): | |
| self.required_permission = required_permission | |
| async def __call__(self, request: Request) -> UserContext: | |
| """Extract and validate user context from request.""" | |
| user_context = getattr(request.state, 'user', None) | |
| if not user_context: | |
| raise HTTPException( | |
| status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | |
| detail="User context not found in request state" | |
| ) | |
| if not user_context.is_authenticated: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Authentication required" | |
| ) | |
| # Check required permission if specified | |
| if self.required_permission: | |
| from shared.auth import permission_checker | |
| permission_checker.require_permission(user_context, self.required_permission) | |
| return user_context | |
| class OptionalAuth: | |
| """Dependency to optionally extract user context (allows anonymous access).""" | |
| async def __call__(self, request: Request) -> Optional[UserContext]: | |
| """Extract user context from request if available.""" | |
| return getattr(request.state, 'user', None) | |
| # Security scheme for OpenAPI documentation | |
| security_scheme = HTTPBearer( | |
| scheme_name="ClerkJWT", | |
| description="Clerk JWT token for authentication" | |
| ) | |
| # Common dependency instances | |
| require_auth = RequireAuth() | |
| require_read_permission = RequireAuth("read_data") | |
| require_write_permission = RequireAuth("write_data") | |
| require_delete_permission = RequireAuth("delete_data") | |
| require_admin_permission = RequireAuth("admin") | |
| optional_auth = OptionalAuth() |