Files
mtusi2026lab3/app/sessions.py
T
2026-11-06 13:32:02 +03:00

130 lines
4.4 KiB
Python

"""Сессии: PostgreSQL — источник истины, Redis — кэш с TTL.
При недоступности Redis работаем напрямую с БД (не принимаем анонимов).
При logout инвалидируем и БД, и кэш.
"""
import logging
import os
from datetime import datetime, timedelta, timezone
from typing import Any
import redis
from psycopg_pool import ConnectionPool
from .security import new_token, token_hash
logger = logging.getLogger("messenger.sessions")
def _now() -> datetime:
return datetime.now(timezone.utc)
def _ttl_seconds() -> int:
return int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
class SessionStore:
def __init__(self, pool: ConnectionPool, cache: redis.Redis | None) -> None:
self.pool = pool
self.cache = cache
# --- кэш --------------------------------------------------------------
def _cache_get(self, th: str) -> dict[str, Any] | None:
if self.cache is None:
return None
try:
raw = self.cache.hgetall("session:" + th)
except redis.RedisError as exc:
logger.warning("redis get failed: %s", type(exc).__name__)
return None
if not raw:
return None
return {
"user_id": raw[b"user_id"].decode(),
"expires_at": raw[b"expires_at"].decode(),
}
def _cache_put(self, th: str, user_id: str, expires_at: datetime) -> None:
if self.cache is None:
return
ttl = max(1, int((expires_at - _now()).total_seconds()))
try:
pipe = self.cache.pipeline()
pipe.hset(
"session:" + th,
mapping={
"user_id": user_id,
"expires_at": expires_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
},
)
pipe.expire("session:" + th, ttl)
pipe.execute()
except redis.RedisError as exc:
logger.warning("redis put failed: %s", type(exc).__name__)
def _cache_del(self, th: str) -> None:
if self.cache is None:
return
try:
self.cache.delete("session:" + th)
except redis.RedisError as exc:
logger.warning("redis del failed: %s", type(exc).__name__)
# --- публичный API ----------------------------------------------------
def create(self, user_id: str) -> dict[str, Any]:
token = new_token()
th = token_hash(token)
expires_at = _now() + timedelta(seconds=_ttl_seconds())
with self.pool.connection() as conn:
with conn.cursor() as cur:
cur.execute(
"INSERT INTO sessions(token_hash, user_id, created_at, expires_at)"
" VALUES (%s, %s, now(), %s)",
(th, user_id, expires_at),
)
conn.commit()
self._cache_put(th, user_id, expires_at)
return {
"token": token,
"expires_at": expires_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
}
def resolve(self, token: str) -> str | None:
"""Возвращает user_id для действующей сессии или None."""
th = token_hash(token)
cached = self._cache_get(th)
if cached is not None:
try:
exp = datetime.strptime(cached["expires_at"], "%Y-%m-%dT%H:%M:%SZ").replace(
tzinfo=timezone.utc
)
except ValueError:
exp = None
if exp is not None and exp > _now():
return cached["user_id"]
self._cache_del(th)
with self.pool.connection() as conn:
with conn.cursor() as cur:
cur.execute(
"SELECT user_id, expires_at FROM sessions WHERE token_hash = %s",
(th,),
)
row = cur.fetchone()
if row is None:
return None
user_id, expires_at = row
if expires_at <= _now():
self.revoke(token)
return None
self._cache_put(th, str(user_id), expires_at)
return str(user_id)
def revoke(self, token: str) -> None:
th = token_hash(token)
with self.pool.connection() as conn:
with conn.cursor() as cur:
cur.execute("DELETE FROM sessions WHERE token_hash = %s", (th,))
conn.commit()
self._cache_del(th)