From 068000515a12f768a9edfab16cc41b25a42d2107 Mon Sep 17 00:00:00 2001 From: mxr612 Date: Wed, 18 Jun 2025 13:33:39 +0800 Subject: [PATCH] refactor: simplify cookie handling in middleware - Updated LanguageMiddleware and UserIdentityMiddleware to always set cookies for language and user ID, respectively, removing conditional checks for existing cookies. This streamlines the cookie management process and ensures consistent behavior across sessions. --- app.py | 33 ++++++++++++++++----------------- database.py | 2 +- 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/app.py b/app.py index 25d8042..31463cf 100644 --- a/app.py +++ b/app.py @@ -88,15 +88,14 @@ class LanguageMiddleware(BaseHTTPMiddleware): # Continue processing the request response = await call_next(request) - # Set cookie if it's not already set or if it's different - if not request.cookies.get("lang") or request.cookies.get("lang") != lang: - response.set_cookie( - key="lang", - value=lang, - max_age=365 * 24 * 60 * 60, # 1 year - httponly=True, - samesite="lax" - ) + # Set cookie + response.set_cookie( + key="lang", + value=lang, + max_age=365 * 24 * 60 * 60, # 1 year + httponly=True, + samesite="lax" + ) return response @@ -129,14 +128,14 @@ class UserIdentityMiddleware(BaseHTTPMiddleware): response = await call_next(request) # Set cookie if it's not already set - if not request.cookies.get("user_id"): - response.set_cookie( - key="user_id", - value=user_id, - max_age=None, # Cookie will never expire - httponly=True, - samesite="lax" - ) + + response.set_cookie( + key="user_id", + value=user_id, + max_age=365 * 24 * 60 * 60, # 1 year + httponly=True, + samesite="lax" + ) return response diff --git a/database.py b/database.py index a9f8821..061f8a3 100644 --- a/database.py +++ b/database.py @@ -54,7 +54,7 @@ def new_user() -> int: user = User() user.last_seen = user.created_at = datetime.now(UTC) db.add(user) - db.flush() + db.commit() return user.id finally: db.close()