Spaces:
Runtime error
Runtime error
Download dependencies/api_auth.py from cloudaiRambo/cloudairambo: direct link, hf CLI and curl.
- Browser
- Download file 1.37 kB
-
https://huggingface.co/spaces/cloudaiRambo/cloudairambo/resolve/main/dependencies/api_auth.py
- Command line
-
hf download hf://spaces/cloudaiRambo/cloudairambo/dependencies/api_auth.py
-
curl -L -o api_auth.py https://huggingface.co/spaces/cloudaiRambo/cloudairambo/resolve/main/dependencies/api_auth.py
1.37 kB
| # dependencies/api_auth.py | |
| import secrets | |
| import os | |
| from fastapi.security import HTTPBasic, HTTPBasicCredentials | |
| from fastapi import Depends, HTTPException, status | |
| # Load credentials securely from environment variables (matching the values in auth.py) | |
| ADMIN_USERNAME = os.environ.get("ADMIN_USER", "admin") | |
| ADMIN_PASSWORD = os.environ.get("ADMIN_PASS", "1234") | |
| # Initialize HTTP Basic Security Scheme | |
| security = HTTPBasic() | |
| def get_current_admin_user(credentials: HTTPBasicCredentials = Depends(security)): | |
| """ | |
| FastAPI dependency function to check HTTP Basic Auth credentials. | |
| This protects API routes (like the ones in routers/stats.py) | |
| that are not part of the starlette-admin dashboard. | |
| """ | |
| # Use secrets.compare_digest for secure, constant-time comparison | |
| is_valid_username = secrets.compare_digest(credentials.username, ADMIN_USERNAME) | |
| is_valid_password = secrets.compare_digest(credentials.password, ADMIN_PASSWORD) | |
| if not (is_valid_username and is_valid_password): | |
| # Raise an exception if authentication fails | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Incorrect username or password", | |
| headers={"WWW-Authenticate": "Basic"}, | |
| ) | |
| # Return the username on success (or any user object if needed) | |
| return credentials.username | |