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 app.database import get_db from app.models import User as UserModel from app.redis_client import get_redis 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\""}) user_id_str = await redis_client.get(f"session:{credentials.credentials}") 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\""}) 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\""}) 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