import re import logging from fastapi import Depends, HTTPException, status from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from sqlalchemy.orm import Session from database import get_db from app.models.auth import Auth_User logger = logging.getLogger(__name__) security = HTTPBearer() def get_current_user( credentials: HTTPAuthorizationCredentials = Depends(security), db: Session = Depends(get_db) ) -> Auth_User: """ Validates the Bearer token and returns the authenticated user. Raises HTTPException 401 if token is invalid or user not found. """ token = credentials.credentials user = db.query(Auth_User).filter(Auth_User.api_key == token).first() if not user: logger.warning("Authentication failed: invalid API key") raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication token", headers={"WWW-Authenticate": "Bearer"}, ) if user.active != 1: logger.warning(f"Authentication failed: user {user.username} is inactive") raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="User account is inactive", headers={"WWW-Authenticate": "Bearer"}, ) return user