Fix auth loop: use TimestampSigner + base64 to match Starlette SessionMiddleware
Browse files6 unmodified lines789101112131415161718192021222324252627282930313233343536373839404142334 unmodified lines3773783793806 unmodified linesfrom starlette.middleware.sessions import SessionMiddlewarefrom starlette.responses import JSONResponse, HTMLResponsefrom starlette.types import ASGIApp, Receive, Scope, Sendfrom itsdangerous import URLSafeSerializer, BadSignatureimport secretsimport timefrom typing import Optional, Callablefrom app.config import settings# Session serializer for decoding cookies in middleware# Must match Starlette's SessionMiddleware exactlydef get_session_serializer():"""Create a serializer matching SessionMiddleware's format exactly"""# Starlette uses URLSafeSerializer (not URLSafeTimedSerializer)# with these exact parametersreturn URLSafeSerializer(settings.SESSION_SECRET_KEY,salt="cookie-session",signer_kwargs={"key_derivation": "hmac","digest_method": "sha1"})def decode_session_cookie(cookie_value: str) -> dict:"""Decode session cookie value to dictionary"""if not cookie_value:return {}try:serializer = get_session_serializer()return serializer.loads(cookie_value)except (BadSignature, Exception) as e:# Log error for debugging but don't crashprint(f"Session decode error: {e}")334 unmodified linesdocument.getElementById('password').focus();</script></body></html>'''6 unmodified lines78910111213141516171819202122232425262728293031323334353637383940414243334 unmodified lines3783793803816 unmodified linesfrom 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}")334 unmodified linesdocument.getElementById('password').focus();</script></body></html>'''
app/auth.py+22-21