forked from mtusi2026/mtusi2026lab3
81 lines
2.9 KiB
Python
81 lines
2.9 KiB
Python
"""Сессии: PostgreSQL — источник истины, Redis/Valkey — read-through кэш."""
|
|
import json
|
|
import time
|
|
from datetime import timezone
|
|
|
|
from . import cache, config, db, security
|
|
from .errors import ApiError
|
|
|
|
TOMBSTONE = "revoked"
|
|
_KEY = "sess:v1:"
|
|
|
|
|
|
def fmt_ts(value):
|
|
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
|
|
|
|
|
def user_json(row):
|
|
return {"id": str(row["id"]), "username": row["username"], "display_name": row["display_name"],
|
|
"created_at": fmt_ts(row["created_at"])}
|
|
|
|
|
|
def _ttl_ms(expires_epoch):
|
|
remaining = expires_epoch - time.time()
|
|
return int(min(config.SESSION_CACHE_TTL_SECONDS, remaining) * 1000) if remaining > 0 else 0
|
|
|
|
|
|
def create(conn, user_row):
|
|
token = security.new_token()
|
|
row = conn.execute(
|
|
"""INSERT INTO sessions (token_hash, user_id, expires_at)
|
|
VALUES (%s, %s, clock_timestamp() + make_interval(secs => %s))
|
|
RETURNING expires_at""",
|
|
(security.token_hash(token), user_row["id"], config.SESSION_TTL_SECONDS)).fetchone()
|
|
conn.execute("""DELETE FROM sessions WHERE token_hash IN (
|
|
SELECT token_hash FROM sessions WHERE expires_at < now() - interval '1 hour' LIMIT 100)""")
|
|
return token, row["expires_at"]
|
|
|
|
|
|
def warm(token, user, expires_at):
|
|
entry = {"user": user, "exp": expires_at.timestamp()}
|
|
ttl = _ttl_ms(entry["exp"])
|
|
if ttl > 0:
|
|
cache.set_if_absent(_KEY + security.token_hash(token).hex(), json.dumps(entry), ttl)
|
|
|
|
|
|
def lookup(token):
|
|
digest = security.token_hash(token)
|
|
key = _KEY + digest.hex()
|
|
cached = cache.get(key)
|
|
if cached == TOMBSTONE:
|
|
return None
|
|
if cached:
|
|
try:
|
|
entry = json.loads(cached)
|
|
if entry["exp"] > time.time():
|
|
return {"user": entry["user"], "digest": digest}
|
|
return None
|
|
except (ValueError, KeyError, TypeError):
|
|
pass
|
|
with db.connection() as conn:
|
|
row = conn.execute(
|
|
"""SELECT u.id, u.username, u.display_name, u.created_at,
|
|
extract(epoch FROM s.expires_at) AS exp
|
|
FROM sessions s JOIN users u ON u.id = s.user_id
|
|
WHERE s.token_hash = %s AND s.expires_at > clock_timestamp()""", (digest,)).fetchone()
|
|
if row is None:
|
|
return None
|
|
user = user_json(row)
|
|
ttl = _ttl_ms(float(row["exp"]))
|
|
if ttl > 0:
|
|
cache.set_if_absent(key, json.dumps({"user": user, "exp": float(row["exp"])}), ttl)
|
|
return {"user": user, "digest": digest}
|
|
|
|
|
|
def revoke(digest):
|
|
if config.CACHE_URL:
|
|
wrote = cache.set_always(_KEY + digest.hex(), TOMBSTONE, config.SESSION_CACHE_TTL_SECONDS * 1000)
|
|
if not wrote:
|
|
raise ApiError(503, "unavailable", "Сервис временно недоступен")
|
|
with db.connection() as conn:
|
|
conn.execute("DELETE FROM sessions WHERE token_hash = %s", (digest,)) |