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=401, detail={"code": "unauthorized", "message": "Missing Bearer token"}, headers={"WWW-Authenticate": "Bearer realm=\"messenger\""}) token = credentials.credentials user_id_str = None try: user_id_str = await redis_client.get(f"session:{token}") except Exception as e: logger.warning(f"Redis unavailable, falling back to PostgreSQL: {e}") 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=401, 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}") raise HTTPException(status_code=500, detail={"code": "internal_error", "message": "Session store unavailable"}) try: user_id = uuid.UUID(user_id_str) except (ValueError, TypeError): raise HTTPException(status_code=401, 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=401, 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=401, detail={"code": "unauthorized", "message": "Missing Basic auth"}, headers={"WWW-Authenticate": "Basic realm=\"messenger\", charset=\"UTF-8\""}) return credentials