cloudairambo / dependencies /api_auth.py
rihancloud's picture
Deploy clean FastAPI backend without node_modules
99fdb5f
Raw History Blame Contribute Delete
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