import base64 import logging from fastapi import Depends, HTTPException, status, Header from fastapi.security import HTTPBasic, HTTPBasicCredentials from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.database import get_db from app.models import User, UserSession from app.redis_client import get_redis logger = logging.getLogger(__name__) security = HTTPBasic() async def get_basic_auth(credentials: HTTPBasicCredentials = Depends(security)): return credentials async def get_current_user( db: AsyncSession = Depends(get_db), redis_client = Depends(get_redis), authorization: str | None = Header(default=None), x_user_id: str | None = Header(default=None, alias="X-User-Id") ): if not authorization: raise HTTPException(status_code=401, detail={"code": "unauthorized", "message": "Missing authorization header"}, headers={"WWW-Authenticate": "Bearer realm=\"messenger\""}) if not authorization.startswith("Bearer "): raise HTTPException(status_code=401, detail={"code": "unauthorized", "message": "Invalid authorization scheme"}, headers={"WWW-Authenticate": "Bearer realm=\"messenger\""}) token = authorization[7:] # Проверяем в Redis сначала try: user_id_str = await redis_client.get(f"session:{token}") if user_id_str: import uuid result = await db.execute(select(User).where(User.id == uuid.UUID(user_id_str))) user = result.scalar_one_or_none() if user: return user except Exception as e: logger.warning(f"Redis unavailable during auth: {e}") # Fallback на PostgreSQL result = await db.execute(select(UserSession).where(UserSession.token == token)) session = result.scalar_one_or_none() if not session: raise HTTPException(status_code=401, detail={"code": "unauthorized", "message": "Invalid or expired session"}, headers={"WWW-Authenticate": "Bearer realm=\"messenger\""}) result = await db.execute(select(User).where(User.id == session.user_id)) user = result.scalar_one_or_none() if not user: raise HTTPException(status_code=401, detail={"code": "unauthorized", "message": "User not found"}) return user