Simplify auth - remove middleware, keep session handling only
Browse files12345667899101112101415111213141920212223242526272829303132333435363738394041424344454647151617188 unmodified lines2728296263303132336768343536373839404142434445461 unmodified line48495076775152535481555657583 unmodified lines626364919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191656667183 unmodified lines251252253381254"""Authentication module for Universal Model TrainerProvides password-based authentication with session managementSIMPLIFIED VERSION - No middleware, direct session checks"""
from fastapi import HTTPException, Request, statusfrom fastapi import HTTPException, Request, status, Dependsfrom starlette.middleware.sessions import SessionMiddlewarefrom starlette.responses import JSONResponse, HTMLResponsefrom starlette.types import ASGIApp, Receive, Scope, Sendfrom itsdangerous import TimestampSigner, BadSignatureimport base64import jsonimport secretsimport timefrom typing import Optional, Callablefrom typing import Optionalfrom app.config import settings
def decode_session_cookie(cookie_value: str) -> dict: """ Decode session cookie value to dictionary. Must match Starlette's SessionMiddleware encoding exactly: 1. TimestampSigner signs the data 2. Data is base64 encoded JSON """ if not cookie_value: return {} try: # Create the same signer that SessionMiddleware uses signer = TimestampSigner( settings.SESSION_SECRET_KEY, salt="cookie-session" ) # Unsign the cookie value unsigned_value = signer.unsign(cookie_value) # Decode base64 and parse JSON decoded = base64.urlsafe_b64decode(unsigned_value) return json.loads(decoded) except (BadSignature, Exception) as e: # Log error for debugging but don't crash print(f"Session decode error: {e}") return {}
def setup_auth(app: ASGIApp) -> None:def setup_auth(app) -> None: """Add session middleware to the FastAPI app""" app.add_middleware( SessionMiddleware,8 unmodified linesdef verify_password(password: str) -> bool: """Verify password against env variable using constant-time comparison""" if not settings.APP_PASSWORD: # No password configured - allow access return True return True # No password configured return secrets.compare_digest(password, settings.APP_PASSWORD)
async def get_current_user(request: Request) -> Optional[dict]: """Check if user is logged in via session"""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 user1 unmodified line
async def require_auth(request: Request) -> dict: """Dependency that requires authentication""" # If no password is configured, allow access """Dependency that requires authentication - returns user or raises 401""" if not settings.APP_PASSWORD: return {"authenticated": True, "username": "anonymous"} user = await get_current_user(request) user = get_current_user(request) if not user: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED,3 unmodified lines return user
class AuthMiddleware: """ Middleware to protect all /api and dashboard routes Allows public access to login, static files, and health checks IMPORTANT: This middleware decodes the session cookie directly because SessionMiddleware hasn't run yet when this middleware executes. Starlette middleware runs in REVERSE order - so AuthMiddleware (added first) runs BEFORE SessionMiddleware (added second). """ # Paths that don't require authentication (exact match) PUBLIC_PATHS = [ "/login", "/api/auth/login", "/api/auth/logout", "/api/auth/check", "/api/auth/status", "/health", "/favicon.ico", ] # Path prefixes that don't require authentication PUBLIC_PREFIXES = [ "/static/", ] def __init__(self, app: ASGIApp): self.app = app async def __call__(self, scope: Scope, receive: Receive, send: Send): # Only handle HTTP requests if scope["type"] != "http": await self.app(scope, receive, send) return path = scope["path"] # Check if auth is configured if not settings.APP_PASSWORD: await self.app(scope, receive, send) return # Allow root path "/" - the dashboard handles its own auth check if path == "/": await self.app(scope, receive, send) return # Allow public paths if path in self.PUBLIC_PATHS: await self.app(scope, receive, send) return # Allow public prefixes for prefix in self.PUBLIC_PREFIXES: if path.startswith(prefix): await self.app(scope, receive, send) return # Check session cookie directly (SessionMiddleware hasn't run yet) headers = dict(scope.get("headers", [])) cookie_header = headers.get(b"cookie", b"").decode("utf-8", errors="ignore") # Parse cookies session_value = None for cookie in cookie_header.split(";"): cookie = cookie.strip() if cookie.startswith("trainer_session="): session_value = cookie.split("=", 1)[1] if "=" in cookie else None break # Decode and check session if session_value: session = decode_session_cookie(session_value) if session.get("user", {}).get("authenticated"): await self.app(scope, receive, send) return # Unauthorized - return appropriate response accept = headers.get(b"accept", b"").decode("utf-8", errors="ignore") # Check if this is an API request or browser request is_api_request = path.startswith("/api/") or "application/json" in accept if is_api_request and "text/html" not in accept: # API request - return JSON error response = JSONResponse( {"detail": "Authentication required", "login_url": "/login"}, status_code=401 ) else: # Browser request - redirect to login response = HTMLResponse( content='<script>window.location.href="/login";</script>', status_code=302, headers={"location": "/login"} ) await response(scope, receive, send)
def is_authenticated(request: Request) -> bool: """Check if request is authenticated (helper for templates)""" if not settings.APP_PASSWORD:183 unmodified lines document.getElementById('password').focus(); </script></body></html>'''</html>'''app/auth.py+18-145