feat: add PostgreSQL fallback for sessions and graceful degradation on Redis failure
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-10-22 16:49:19 +03:00
parent cca293dcb1
commit 566b02d850
9 changed files with 479 additions and 128 deletions
+77 -9
View File
@@ -1,29 +1,97 @@
import uuid
import logging
from datetime import datetime, timezone
from fastapi import Depends, HTTPException, status, Security
from fastapi.security import HTTPBearer, HTTPBasic, HTTPBasicCredentials
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
import uuid
from sqlalchemy.exc import SQLAlchemyError
from app.database import get_db
from app.models import User as UserModel
from app.models import User as UserModel, UserSession
from app.redis_client import get_redis
logger = logging.getLogger(__name__)
security_bearer = HTTPBearer(auto_error=False)
security_basic = HTTPBasic(auto_error=False)
async def get_current_user(credentials = Security(security_bearer), db: AsyncSession = Depends(get_db), redis_client = Depends(get_redis)) -> UserModel:
async def get_current_user(
credentials = Security(security_bearer),
db: AsyncSession = Depends(get_db),
redis_client = Depends(get_redis)
) -> UserModel:
if not credentials:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail={"code": "unauthorized", "message": "Missing Bearer token"}, headers={"WWW-Authenticate": "Bearer realm=\"messenger\""})
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail={"code": "unauthorized", "message": "Missing Bearer token"},
headers={"WWW-Authenticate": "Bearer realm=\"messenger\""}
)
user_id_str = await redis_client.get(f"session:{credentials.credentials}")
token = credentials.credentials
user_id_str = None
# 1. Пытаемся получить сессию из Redis
try:
user_id_str = await redis_client.get(f"session:{token}")
except Exception as e:
logger.warning(f"Redis unavailable for session lookup, falling back to PostgreSQL: {e}")
# 2. Если Redis недоступен или сессия не найдена — проверяем PostgreSQL
if not user_id_str:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail={"code": "unauthorized", "message": "Invalid or expired session"}, headers={"WWW-Authenticate": "Bearer realm=\"messenger\""})
try:
result = await db.execute(
select(UserSession)
.where(UserSession.token == token)
.where(UserSession.expires_at > datetime.now(timezone.utc))
)
session = result.scalar_one_or_none()
if session:
user_id_str = str(session.user_id)
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail={"code": "unauthorized", "message": "Invalid or expired session"},
headers={"WWW-Authenticate": "Bearer realm=\"messenger\""}
)
except HTTPException:
raise
except SQLAlchemyError as e:
logger.error(f"PostgreSQL error during session check: {e}")
# Возвращаем 500, так как этот код описан в контракте как internal_error
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail={"code": "internal_error", "message": "Session store unavailable"}
)
# 3. Получаем пользователя из БД
try:
user_id = uuid.UUID(user_id_str)
except (ValueError, TypeError):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail={"code": "unauthorized", "message": "Invalid session data"},
headers={"WWW-Authenticate": "Bearer realm=\"messenger\""}
)
result = await db.execute(select(UserModel).where(UserModel.id == user_id))
user = result.scalar_one_or_none()
user = (await db.execute(select(UserModel).where(UserModel.id == uuid.UUID(user_id_str)))).scalar_one_or_none()
if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail={"code": "unauthorized", "message": "User not found"}, headers={"WWW-Authenticate": "Bearer realm=\"messenger\""})
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail={"code": "unauthorized", "message": "User not found"},
headers={"WWW-Authenticate": "Bearer realm=\"messenger\""}
)
return user
def get_basic_auth(credentials: HTTPBasicCredentials = Security(security_basic)):
if not credentials:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail={"code": "unauthorized", "message": "Missing Basic auth"}, headers={"WWW-Authenticate": "Basic realm=\"messenger\", charset=\"UTF-8\""})
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail={"code": "unauthorized", "message": "Missing Basic auth"},
headers={"WWW-Authenticate": "Basic realm=\"messenger\", charset=\"UTF-8\""}
)
return credentials