35 lines
931 B
Python
35 lines
931 B
Python
import secrets
|
|
|
|
from passlib.context import CryptContext
|
|
from starlette.requests import Request
|
|
from fastapi import HTTPException, status
|
|
|
|
from app.config import get_config
|
|
|
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
|
|
|
|
|
|
|
def verify_credentials(username: str, password: str) -> bool:
|
|
cfg = get_config()
|
|
username_ok = secrets.compare_digest(username, cfg.app_username)
|
|
if not username_ok:
|
|
return False
|
|
|
|
if cfg.app_password_hash:
|
|
return pwd_context.verify(password, cfg.app_password_hash)
|
|
|
|
return secrets.compare_digest(password, cfg.app_password)
|
|
|
|
|
|
|
|
def require_auth(request: Request) -> str:
|
|
username = request.session.get("username")
|
|
cfg = get_config()
|
|
if not username or username != cfg.app_username:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Authentication required",
|
|
)
|
|
return username
|