forked from mtusi2026/mtusi2026lab2
149 lines
5.4 KiB
Python
149 lines
5.4 KiB
Python
"""
|
|
Сессии: PostgreSQL — источник истины, Redis/Valkey — кэш поиска сессии.
|
|
|
|
Чтение (проверка Bearer):
|
|
1. Ищем в Redis ключ sess:<sha256(token)>. Нашли и не истёк → пользователь.
|
|
2. Нет в кэше / Redis недоступен → читаем sessions в PostgreSQL
|
|
(не отозвана и expires_at > now()) и кладём результат в кэш.
|
|
|
|
Политика expiry: срок жизни сессии задаёт PostgreSQL (expires_at).
|
|
TTL ключа в Redis = min(SESSION_CACHE_TTL_SECONDS, время до expires_at),
|
|
поэтому кэш никогда не продлевает сессию.
|
|
|
|
Инвалидация: logout сначала помечает revoked_at в PostgreSQL, затем удаляет
|
|
ключ из Redis. Отозванную сессию из кэша больше не прочитать.
|
|
|
|
Отказ Redis: кэш обходится, всё читается из PostgreSQL (медленнее, но верно).
|
|
Flush/рестарт Redis: кэш пустой → сессии восстанавливаются из PostgreSQL.
|
|
Отказ PostgreSQL: новые проверки идут в БД → 503, анонимный запрос не принимается.
|
|
"""
|
|
from __future__ import annotations
|
|
import json
|
|
import logging
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
import redis.asyncio as aioredis
|
|
from redis.exceptions import RedisError
|
|
|
|
from .config import settings
|
|
from .security import new_token, token_hash
|
|
|
|
log = logging.getLogger("messenger.sessions")
|
|
|
|
_redis: aioredis.Redis | None = None
|
|
|
|
|
|
def init_redis() -> None:
|
|
global _redis
|
|
if settings.redis_url:
|
|
_redis = aioredis.Redis.from_url(
|
|
settings.redis_url,
|
|
socket_timeout=settings.redis_timeout,
|
|
socket_connect_timeout=settings.redis_timeout,
|
|
decode_responses=True,
|
|
)
|
|
|
|
|
|
async def close_redis() -> None:
|
|
if _redis is not None:
|
|
await _redis.aclose()
|
|
|
|
|
|
def redis_enabled() -> bool:
|
|
return _redis is not None
|
|
|
|
|
|
async def redis_ping() -> bool:
|
|
if _redis is None:
|
|
return False
|
|
try:
|
|
return bool(await _redis.ping())
|
|
except (RedisError, OSError):
|
|
return False
|
|
|
|
|
|
def _key(th: bytes) -> str:
|
|
return "sess:" + th.hex()
|
|
|
|
|
|
async def _cache_get(th: bytes) -> dict | None:
|
|
if _redis is None:
|
|
return None
|
|
try:
|
|
raw = await _redis.get(_key(th))
|
|
except (RedisError, OSError) as exc:
|
|
log.warning("redis unavailable on read, bypassing cache: %s", type(exc).__name__)
|
|
return None
|
|
return json.loads(raw) if raw else None
|
|
|
|
|
|
async def _cache_put(th: bytes, user: dict, expires_at: datetime) -> None:
|
|
if _redis is None:
|
|
return
|
|
left = int((expires_at - datetime.now(timezone.utc)).total_seconds())
|
|
ttl = min(settings.session_cache_ttl_seconds, left)
|
|
if ttl <= 0:
|
|
return
|
|
try:
|
|
await _redis.set(_key(th), json.dumps({"user": user, "exp": expires_at.isoformat()}), ex=ttl)
|
|
except (RedisError, OSError) as exc:
|
|
log.warning("redis unavailable on write, skipping cache: %s", type(exc).__name__)
|
|
|
|
|
|
async def _cache_delete(th: bytes) -> None:
|
|
if _redis is None:
|
|
return
|
|
try:
|
|
await _redis.delete(_key(th))
|
|
except (RedisError, OSError) as exc:
|
|
# Сессия уже отозвана в PostgreSQL. Если Redis пережил сбой с данными,
|
|
# устаревший ключ проживёт не дольше SESSION_CACHE_TTL_SECONDS.
|
|
log.warning("redis unavailable on invalidate: %s", type(exc).__name__)
|
|
|
|
|
|
async def create_session(conn, user_id) -> tuple[str, datetime]:
|
|
token = new_token()
|
|
now = datetime.now(timezone.utc)
|
|
expires_at = now + timedelta(seconds=settings.session_ttl_seconds)
|
|
await conn.execute(
|
|
"INSERT INTO sessions (token_hash, user_id, created_at, expires_at) "
|
|
"VALUES (%s, %s, %s, %s)",
|
|
(token_hash(token), user_id, now, expires_at))
|
|
return token, expires_at
|
|
|
|
|
|
async def resolve(pool, token: str, load_user) -> dict | None:
|
|
"""Вернёт пользователя (dict) для действующего токена или None."""
|
|
th = token_hash(token)
|
|
cached = await _cache_get(th)
|
|
if cached is not None:
|
|
if datetime.fromisoformat(cached["exp"]) > datetime.now(timezone.utc):
|
|
return cached["user"]
|
|
return None
|
|
async with pool.connection() as conn:
|
|
cur = await conn.execute(
|
|
"SELECT user_id, expires_at FROM sessions "
|
|
"WHERE token_hash = %s AND revoked_at IS NULL AND expires_at > now()",
|
|
(th,))
|
|
row = await cur.fetchone()
|
|
if row is None:
|
|
return None
|
|
user = await load_user(conn, row[0])
|
|
if user is None:
|
|
return None
|
|
await _cache_put(th, user, row[1])
|
|
return user
|
|
|
|
|
|
async def revoke(pool, token: str) -> bool:
|
|
"""Отозвать сессию. True — была действующая и теперь отозвана."""
|
|
th = token_hash(token)
|
|
async with pool.connection() as conn:
|
|
cur = await conn.execute(
|
|
"UPDATE sessions SET revoked_at = now() "
|
|
"WHERE token_hash = %s AND revoked_at IS NULL AND expires_at > now() "
|
|
"RETURNING 1", (th,))
|
|
ok = await cur.fetchone() is not None
|
|
await _cache_delete(th)
|
|
return ok
|