""" Authentication module for Universal Model Trainer Provides password-based authentication with session management SIMPLIFIED VERSION - No middleware, direct session checks """ from fastapi import HTTPException, Request, status, Depends from starlette.middleware.sessions import SessionMiddleware from starlette.responses import JSONResponse, HTMLResponse import secrets from typing import Optional from app.config import settings def setup_auth(app) -> None: """Add session middleware to the FastAPI app""" app.add_middleware( SessionMiddleware, secret_key=settings.SESSION_SECRET_KEY, session_cookie="trainer_session", max_age=settings.SESSION_EXPIRE_HOURS * 3600, same_site="lax", https_only=False # Set to True in production with HTTPS ) def verify_password(password: str) -> bool: """Verify password against env variable using constant-time comparison""" if not settings.APP_PASSWORD: return True # No password configured return secrets.compare_digest(password, settings.APP_PASSWORD) def is_auth_enabled() -> bool: """Check if authentication is enabled""" return bool(settings.APP_PASSWORD) def get_current_user(request: Request) -> Optional[dict]: """Get current user from session if authenticated""" if not settings.APP_PASSWORD: return {"authenticated": True, "username": "anonymous"} user = request.session.get("user") if user and user.get("authenticated"): return user return None async def require_auth(request: Request) -> dict: """Dependency that requires authentication - returns user or raises 401""" if not settings.APP_PASSWORD: return {"authenticated": True, "username": "anonymous"} user = get_current_user(request) if not user: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Authentication required", headers={"WWW-Authenticate": "Session"} ) return user def is_authenticated(request: Request) -> bool: """Check if request is authenticated (helper for templates)""" if not settings.APP_PASSWORD: return True user = request.session.get("user") return bool(user and user.get("authenticated")) def get_login_html(error: str = None) -> str: """Generate the login page HTML""" error_display = f'
{error}
' if error else '
Invalid password
' return f''' Universal Model Trainer - Login

Universal Model Trainer

Enter your password to access the training dashboard

{error_display}
'''