forked from mtusi2026/mtusi2026lab2
[+] add project
This commit is contained in:
+52
-9
@@ -6,6 +6,7 @@ import logging
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime, timedelta, timezone
|
||||
@@ -326,15 +327,45 @@ def authenticated_user(
|
||||
raise auth_error()
|
||||
# PostgreSQL remains authoritative for expiry and revocation. Redis avoids
|
||||
# a user-profile query on a cache hit.
|
||||
if cached and cached.get("user_id") == str(session["user_id"]):
|
||||
if cached:
|
||||
profile = cached.get("user")
|
||||
if isinstance(profile, dict) and profile.get("id") == str(session["user_id"]):
|
||||
if (
|
||||
cached.get("user_id") == str(session["user_id"])
|
||||
and isinstance(profile, dict)
|
||||
and profile.get("id") == str(session["user_id"])
|
||||
):
|
||||
user = profile
|
||||
else:
|
||||
cached = None
|
||||
else:
|
||||
cached = None
|
||||
lock_key = cache_key + ":fill-lock"
|
||||
lock_token = str(uuid.uuid4())
|
||||
lock_acquired = False
|
||||
if not cached:
|
||||
for _ in range(20):
|
||||
try:
|
||||
lock_acquired = bool(
|
||||
cache.set(lock_key, lock_token, nx=True, px=5000)
|
||||
)
|
||||
if lock_acquired:
|
||||
break
|
||||
raw = cache.get(cache_key)
|
||||
if raw:
|
||||
cached_value = json.loads(raw)
|
||||
if (
|
||||
isinstance(cached_value, dict)
|
||||
and cached_value.get("user_id") == str(session["user_id"])
|
||||
and isinstance(cached_value.get("user"), dict)
|
||||
and cached_value["user"].get("id") == str(session["user_id"])
|
||||
):
|
||||
user = cached_value["user"]
|
||||
cached = cached_value
|
||||
break
|
||||
except (redis.RedisError, json.JSONDecodeError):
|
||||
logger.warning("session cache single-flight failed; using PostgreSQL")
|
||||
break
|
||||
time.sleep(0.05)
|
||||
if not cached:
|
||||
logger.info("profile_cache_fill request_id=%s", request.state.request_id)
|
||||
profile_row = connection.execute(
|
||||
"""
|
||||
SELECT id, username, display_name, created_at
|
||||
@@ -346,14 +377,26 @@ def authenticated_user(
|
||||
raise auth_error()
|
||||
user = user_json(profile_row)
|
||||
remaining = max(1, int((session["expires_at"] - now).total_seconds()))
|
||||
if lock_acquired:
|
||||
try:
|
||||
cache.set(
|
||||
cache_key,
|
||||
json.dumps({"user_id": str(session["user_id"]), "user": user}),
|
||||
ex=remaining,
|
||||
)
|
||||
except redis.RedisError:
|
||||
logger.warning("session cache write failed; continuing with PostgreSQL")
|
||||
if lock_acquired:
|
||||
try:
|
||||
cache.set(
|
||||
cache_key,
|
||||
json.dumps({"user_id": str(session["user_id"]), "user": user}),
|
||||
ex=remaining,
|
||||
cache.eval(
|
||||
"if redis.call('get', KEYS[1]) == ARGV[1] "
|
||||
"then return redis.call('del', KEYS[1]) else return 0 end",
|
||||
1,
|
||||
lock_key,
|
||||
lock_token,
|
||||
)
|
||||
except redis.RedisError:
|
||||
logger.warning("session cache write failed; continuing with PostgreSQL")
|
||||
logger.warning("session cache fill lock release failed")
|
||||
request.state.token_hash = token_hash
|
||||
return user
|
||||
|
||||
|
||||
Reference in New Issue
Block a user