Simplify auth - remove middleware, keep session handling only
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849508 unmodified lines596061626364656667686970711 unmodified line7374757677787980818283843 unmodified lines888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194183 unmodified lines378379380381"""Authentication module for Universal Model TrainerProvides password-based authentication with session management"""from fastapi import HTTPException, Request, statusfrom 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 app.config import settingsdef decode_session_cookie(cookie_value: str) -> dict:"""Decode session cookie value to dictionary.Must match Starlette's SessionMiddleware encoding exactly:1. TimestampSigner signs the data2. Data is base64 encoded JSON"""if not cookie_value:return {}try:# Create the same signer that SessionMiddleware usessigner = TimestampSigner(settings.SESSION_SECRET_KEY,salt="cookie-session")# Unsign the cookie valueunsigned_value = signer.unsign(cookie_value)# Decode base64 and parse JSONdecoded = base64.urlsafe_b64decode(unsigned_value)return json.loads(decoded)except (BadSignature, Exception) as e:# Log error for debugging but don't crashprint(f"Session decode error: {e}")return {}def setup_auth(app: ASGIApp) -> 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 accessreturn Truereturn secrets.compare_digest(password, settings.APP_PASSWORD)async def get_current_user(request: Request) -> Optional[dict]:"""Check if user is logged in via session"""user = request.session.get("user")if user and user.get("authenticated"):return user1 unmodified lineasync def require_auth(request: Request) -> dict:"""Dependency that requires authentication"""# If no password is configured, allow accessif not settings.APP_PASSWORD:return {"authenticated": True, "username": "anonymous"}user = await get_current_user(request)if not user:raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,3 unmodified linesreturn userclass AuthMiddleware:"""Middleware to protect all /api and dashboard routesAllows public access to login, static files, and health checksIMPORTANT: This middleware decodes the session cookie directly becauseSessionMiddleware 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 authenticationPUBLIC_PREFIXES = ["/static/",]def __init__(self, app: ASGIApp):self.app = appasync def __call__(self, scope: Scope, receive: Receive, send: Send):# Only handle HTTP requestsif scope["type"] != "http":await self.app(scope, receive, send)returnpath = scope["path"]# Check if auth is configuredif not settings.APP_PASSWORD:await self.app(scope, receive, send)return# Allow root path "/" - the dashboard handles its own auth checkif path == "/":await self.app(scope, receive, send)return# Allow public pathsif path in self.PUBLIC_PATHS:await self.app(scope, receive, send)return# Allow public prefixesfor 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 cookiessession_value = Nonefor cookie in cookie_header.split(";"):cookie = cookie.strip()if cookie.startswith("trainer_session="):session_value = cookie.split("=", 1)[1] if "=" in cookie else Nonebreak# Decode and check sessionif session_value:session = decode_session_cookie(session_value)if session.get("user", {}).get("authenticated"):await self.app(scope, receive, send)return# Unauthorized - return appropriate responseaccept = headers.get(b"accept", b"").decode("utf-8", errors="ignore")# Check if this is an API request or browser requestis_api_request = path.startswith("/api/") or "application/json" in acceptif is_api_request and "text/html" not in accept:# API request - return JSON errorresponse = JSONResponse({"detail": "Authentication required", "login_url": "/login"},status_code=401)else:# Browser request - redirect to loginresponse = 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 linesdocument.getElementById('password').focus();</script></body></html>'''1234567891011121314151617188 unmodified lines27282930313233343536373839404142434445461 unmodified line48495051525354555657583 unmodified lines626364656667183 unmodified lines251252253254"""Authentication module for Universal Model TrainerProvides password-based authentication with session managementSIMPLIFIED VERSION - No middleware, direct session checks"""from fastapi import HTTPException, Request, status, Dependsfrom starlette.middleware.sessions import SessionMiddlewarefrom starlette.responses import JSONResponse, HTMLResponseimport secretsfrom typing import Optionalfrom app.config import settingsdef 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:return True # No password configuredreturn 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 user1 unmodified lineasync 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,3 unmodified linesreturn userdef is_authenticated(request: Request) -> bool:"""Check if request is authenticated (helper for templates)"""if not settings.APP_PASSWORD:183 unmodified linesdocument.getElementById('password').focus();</script></body></html>'''
app/auth.py+18-145