97 lines
3.7 KiB
Python
97 lines
3.7 KiB
Python
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
|
|
from sqlalchemy.exc import SQLAlchemyError
|
|
|
|
from app.database import get_db
|
|
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:
|
|
if not credentials:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail={"code": "unauthorized", "message": "Missing Bearer token"},
|
|
headers={"WWW-Authenticate": "Bearer realm=\"messenger\""}
|
|
)
|
|
|
|
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:
|
|
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()
|
|
|
|
if not user:
|
|
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\""}
|
|
)
|
|
return credentials |