""" Authentication Dependency for FastAPI Provides dependency to get current authenticated user from JWT token """ from fastapi import Depends, HTTPException, status from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from typing import Optional import sys import os sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from services.auth import auth_service security = HTTPBearer() async def get_current_user( credentials: HTTPAuthorizationCredentials = Depends(security) ) -> str: """ Dependency to get the current authenticated user from JWT token. Raises HTTPException if token is invalid or missing. """ token = credentials.credentials username = auth_service.verify_token(token) if username is None: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication credentials", headers={"WWW-Authenticate": "Bearer"}, ) return username async def get_current_user_optional( credentials: Optional[HTTPAuthorizationCredentials] = Depends(HTTPBearer(auto_error=False)) ) -> Optional[str]: """ Optional dependency to get current user if token is provided. Returns None if no token or invalid token. """ if credentials is None: return None token = credentials.credentials username = auth_service.verify_token(token) return username