lab3
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
"""Сессии в Valkey. Ключ — SHA-256 токена, TTL равен остатку жизни сессии.
|
||||
|
||||
Источник истины сессий — общий Valkey, не память процесса API.
|
||||
AOF и volume сохраняют ключ при перезапуске хранилища.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import redis
|
||||
|
||||
from errors import ApiError
|
||||
|
||||
_client: redis.Redis | None = None
|
||||
|
||||
|
||||
def session_ttl() -> int:
|
||||
raw = os.environ.get("SESSION_TTL_SECONDS", "3600")
|
||||
try:
|
||||
value = int(raw)
|
||||
except ValueError:
|
||||
return 3600
|
||||
return value if value >= 1 else 1
|
||||
|
||||
|
||||
def redis_url() -> str:
|
||||
path = os.environ.get("CACHE_URL_FILE", "").strip()
|
||||
if path and Path(path).is_file():
|
||||
return Path(path).read_text(encoding="utf-8").strip()
|
||||
return os.environ.get("REDIS_URL", "").strip()
|
||||
|
||||
|
||||
def init() -> None:
|
||||
global _client
|
||||
url = redis_url()
|
||||
if not url:
|
||||
_client = None
|
||||
return
|
||||
_client = redis.Redis.from_url(
|
||||
url, socket_connect_timeout=0.5, socket_timeout=0.5,
|
||||
decode_responses=True)
|
||||
|
||||
|
||||
def _key(token: str) -> str:
|
||||
digest = hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
return "session:" + digest
|
||||
|
||||
|
||||
def _require() -> redis.Redis:
|
||||
if _client is None:
|
||||
raise ApiError(503, "unavailable", "Хранилище сессий недоступно")
|
||||
return _client
|
||||
|
||||
|
||||
def ping() -> bool:
|
||||
try:
|
||||
return bool(_require().ping())
|
||||
except (ApiError, redis.RedisError):
|
||||
return False
|
||||
|
||||
|
||||
def create(token: str, user_id: str, ttl: int) -> None:
|
||||
try:
|
||||
_require().set(_key(token), user_id, ex=ttl)
|
||||
except (ApiError, redis.RedisError) as exc:
|
||||
raise ApiError(503, "unavailable", "Хранилище сессий недоступно") from exc
|
||||
|
||||
|
||||
def user_id(token: str) -> str:
|
||||
try:
|
||||
value = _require().get(_key(token))
|
||||
except (ApiError, redis.RedisError) as exc:
|
||||
raise ApiError(503, "unavailable", "Хранилище сессий недоступно") from exc
|
||||
if not value:
|
||||
raise ApiError(401, "unauthorized", "Сессия недействительна")
|
||||
return value
|
||||
|
||||
|
||||
def revoke(token: str) -> None:
|
||||
try:
|
||||
_require().delete(_key(token))
|
||||
except (ApiError, redis.RedisError) as exc:
|
||||
raise ApiError(503, "unavailable", "Хранилище сессий недоступно") from exc
|
||||
Reference in New Issue
Block a user