from fastapi import Request, HTTPException
from starlette.middleware.base import BaseHTTPMiddleware
import re

class InputSanitizationMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        sanitized_query_params = {
            key: self.sanitize_input(value) for key, value in request.query_params.items()
        }
        
        # Create a new request with sanitized query parameters
        request.scope["query_string"] = "&".join(
            [f"{key}={value}" for key, value in sanitized_query_params.items()]
        ).encode("utf-8")
        
        response = await call_next(request)
        return response

    def sanitize_input(self, input_str: str) -> str:
        sanitized_str = re.sub(r"[;\\']", '', input_str)
        return sanitized_str
