Creative_Breakthrough / services /auth_dependency.py
sushilideaclan01's picture
Initial commit of the Ad Generator Lite project, including backend services, frontend components, and configuration files. Added core functionalities for ad generation, user management, and image processing, along with a structured matrix system for ad testing.
f201243
"""
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