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.
This commit is contained in:
Miu Li 2025-06-18 13:33:39 +08:00
parent 1bd19235e0
commit 068000515a
2 changed files with 17 additions and 18 deletions

33
app.py
View File

@ -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

View File

@ -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()