Spaces:
Sleeping
Sleeping
| """ | |
| Simple token-based authentication module. | |
| Uses a secret API token stored as environment variable. | |
| """ | |
| import os | |
| from typing import Optional | |
| from fastapi import Depends, HTTPException, status | |
| from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials | |
| # Security scheme - auto_error=False allows unauthenticated requests to pass through | |
| security = HTTPBearer(auto_error=False) | |
| # Get API token from environment variable (set as HuggingFace secret) | |
| API_SECRET_TOKEN = os.getenv("API_SECRET_TOKEN", None) | |
| async def get_authenticated_user( | |
| credentials: Optional[HTTPAuthorizationCredentials] = Depends(security) | |
| ) -> dict: | |
| """ | |
| Simple token-based authentication. | |
| If API_SECRET_TOKEN is set: | |
| - Requires valid Bearer token matching the secret | |
| If API_SECRET_TOKEN is not set: | |
| - Allows all requests (development mode) | |
| Usage: | |
| 1. Set API_SECRET_TOKEN as a HuggingFace Space secret | |
| 2. Send requests with header: Authorization: Bearer <your-token> | |
| """ | |
| # If no secret is configured, allow all requests (dev mode) | |
| if not API_SECRET_TOKEN: | |
| return { | |
| "user_id": "anonymous", | |
| "email": "[email protected]", | |
| "name": "Anonymous User", | |
| "authenticated": False | |
| } | |
| # Secret is configured - require valid token | |
| if not credentials: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Authentication required. Provide Bearer token.", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| # Validate token | |
| if credentials.credentials != API_SECRET_TOKEN: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid authentication token", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| # Token is valid | |
| return { | |
| "user_id": "api_user", | |
| "email": "[email protected]", | |
| "name": "API User", | |
| "authenticated": True | |
| } | |
| async def get_optional_user( | |
| credentials: Optional[HTTPAuthorizationCredentials] = Depends(security) | |
| ) -> Optional[dict]: | |
| """ | |
| Optional authentication - doesn't require credentials. | |
| Returns user info if authenticated, None otherwise. | |
| """ | |
| if not API_SECRET_TOKEN: | |
| return None | |
| if credentials and credentials.credentials == API_SECRET_TOKEN: | |
| return { | |
| "user_id": "api_user", | |
| "email": "[email protected]", | |
| "name": "API User", | |
| "authenticated": True | |
| } | |
| return None | |