File size: 1,373 Bytes
99fdb5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# 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