Initial import
This commit is contained in:
0
backend/core/__init__.py
Normal file
0
backend/core/__init__.py
Normal file
32
backend/core/redis.py
Normal file
32
backend/core/redis.py
Normal file
@@ -0,0 +1,32 @@
|
||||
import os
|
||||
from redis.asyncio import Redis, from_url
|
||||
|
||||
# Берем URL из окружения или ставим дефолт для нашей docker-сети
|
||||
REDIS_URL = os.getenv("REDIS_URL", "redis://redis:6379/0")
|
||||
|
||||
# Глобальный пул соединений
|
||||
redis_client: Redis = from_url(REDIS_URL, decode_responses=True)
|
||||
|
||||
async def get_redis() -> Redis:
|
||||
return redis_client
|
||||
|
||||
async def acquire_seat_lock(seat_id: int, user_id: int, ttl_seconds: int = 900) -> bool:
|
||||
"""
|
||||
Пытается захватить блокировку на место.
|
||||
ttl_seconds = 900 (15 минут на оплату по ТЗ).
|
||||
Возвращает True, если блокировка получена, иначе False.
|
||||
"""
|
||||
lock_key = f"lock:seat:{seat_id}"
|
||||
|
||||
# SETNX: Set if Not eXists. Если ключ есть, вернет None/False
|
||||
# ex: устанавливает время жизни ключа (TTL)
|
||||
is_locked = await redis_client.set(lock_key, str(user_id), nx=True, ex=ttl_seconds)
|
||||
|
||||
return bool(is_locked)
|
||||
|
||||
async def release_seat_lock(seat_id: int) -> None:
|
||||
"""
|
||||
Принудительно снимает блокировку (например, при отмене или ошибке БД).
|
||||
"""
|
||||
lock_key = f"lock:seat:{seat_id}"
|
||||
await redis_client.delete(lock_key)
|
||||
34
backend/core/security.py
Normal file
34
backend/core/security.py
Normal file
@@ -0,0 +1,34 @@
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import jwt
|
||||
from passlib.context import CryptContext
|
||||
|
||||
SECRET_KEY: str = os.environ["JWT_SECRET_KEY"]
|
||||
ALGORITHM: str = os.getenv("JWT_ALGORITHM", "HS256")
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = int(os.getenv("JWT_ACCESS_TOKEN_EXPIRE_MINUTES", "60"))
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
|
||||
def hash_password(plain: str) -> str:
|
||||
return pwd_context.hash(plain)
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
return pwd_context.verify(plain, hashed)
|
||||
|
||||
|
||||
def create_access_token(subject: int | str) -> str:
|
||||
expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
payload = {"sub": str(subject), "exp": expire}
|
||||
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
|
||||
|
||||
|
||||
def decode_access_token(token: str) -> str:
|
||||
"""Декодирует токен и возвращает sub (user_id). Бросает jwt.PyJWTError при невалидном токене."""
|
||||
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
||||
sub: str | None = payload.get("sub")
|
||||
if sub is None:
|
||||
raise jwt.InvalidTokenError("Token payload missing 'sub'")
|
||||
return sub
|
||||
Reference in New Issue
Block a user