Middleware

 
""" FastAPI app definition & router includes
"""

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from dotenv import load_dotenv
import logging
import os

# * Load .evn (explicit path for Windows Service)
load_dotenv(r"D:\fastapi-service\.env")

# * Logging configuration
logging.basicConfig(
    level=os.getenv("LOG_LEVEL", "INFO").upper(),
    filename=os.getenv("LOG_FILE", "d:/fastapi-service/logs/service.log"),
    filemode="a",
    format="%(asctime)s %(levelname)s [%(name)s] %(message)s",
    datefmt="%Y-%m-%h %H:%M:%S"
)

app = FastAPI(title="PPF Automations API", root_path="/fastapi")
logger = logging.getLogger(__name__)

# Routers
from app.endpoints import router_hello_world, router_import_mtm_options
app.include_router(router_hello_world.router, prefix="/hello_world", tags=["Hello World"])
app.include_router(router_import_my_options.router, prefix="/import_my_options", tags=["File Parsers"])

# Allowed IPs
ALLOWED_IPS = {ip for ip in os.getenv("ALLOWED_IPS").split(",")}

@app.middleware("http")
async def id_denied_middleware(request: Request, call_next):
    client_ip = request.client.host

    if client_ip not in ALLOWED_IPS:
        logger.warning(f"DENY from {client_ip}")
        return JSONResponse({"status":"error", "output": f"Access denied from IP {client_ip}"})

    response = await call_next(request)
    logger.info(f"Response: {response.status_code} for {request.url.path} {client_ip}")
    return response