Update via HuggingFace Tool
Browse files6 unmodified lines78910101112131 unmodified line1516171819192020212223242523262728293031323 unmodified lines3637383334353940414243444548 unmodified lines9495969798991009210110210310425 unmodified lines13013113212413313413513613713813914014123 unmodified lines16516616715416816917017117217316017417517617764 unmodified lines24224324423124524624724899 unmodified lines34834935033735135235335435535635735834435936034634736136236336436511 unmodified lines3773783793653806 unmodified linesfrom starlette.middleware.sessions import SessionMiddlewarefrom starlette.responses import JSONResponse, HTMLResponsefrom starlette.types import ASGIApp, Receive, Scope, Sendfrom itsdangerous import URLSafeTimedSerializer, BadSignaturefrom itsdangerous import URLSafeSerializer, BadSignatureimport secretsimport timefrom typing import Optional, Callable1 unmodified line
# Session serializer for decoding cookies in middleware# Must match Starlette's SessionMiddleware exactlydef get_session_serializer(): """Create a serializer matching SessionMiddleware's format""" return URLSafeTimedSerializer( """Create a serializer matching SessionMiddleware's format exactly""" # Starlette uses URLSafeSerializer (not URLSafeTimedSerializer) # with these exact parameters return URLSafeSerializer( settings.SESSION_SECRET_KEY, salt="cookie-session", signer_kwargs={"key_derivation": "hmac", "digest_method": "sha1"} signer_kwargs={ "key_derivation": "hmac", "digest_method": "sha1" } )
3 unmodified lines return {} try: serializer = get_session_serializer() # max_age matches the session max_age return serializer.loads(cookie_value, max_age=settings.SESSION_EXPIRE_HOURS * 3600) except (BadSignature, Exception): return serializer.loads(cookie_value) except (BadSignature, Exception) as e: # Log error for debugging but don't crash print(f"Session decode error: {e}") return {}
48 unmodified lines 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 # Paths that don't require authentication (exact match) PUBLIC_PATHS = [ "/login", "/api/auth/login",25 unmodified lines await self.app(scope, receive, send) return # Allow public paths (but NOT root "/") # 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) return23 unmodified lines await self.app(scope, receive, send) return # Unauthorized - redirect to login for HTML requests # 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 not "text/html" 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"},64 unmodified lines }} .login-icon {{ font-size: 3rem; margin-bottom: 20px; margin-bottom: 20px; display: block; text-align: center; }}99 unmodified lines const response = await fetch('/api/auth/login', {{ method: 'POST', body: formData body: formData, credentials: 'same-origin' }}); const data = await response.json(); if (response.ok && data.success) {{ btnText.textContent = 'Success!'; // Wait a moment for cookie to be set, then redirect // Wait for cookie to be fully set, then redirect setTimeout(() => {{ window.location.href = '/'; }}, 100); window.location.replace('/'); }}, 200); }} else {{ throw new Error(data.detail || 'Authentication failed'); }}11 unmodified lines document.getElementById('password').focus(); </script></body></html>'''</html>'''app/auth.py+32-17