Files
saura_shakti_website/backend/app/main.py
T
Shubhankar45 53dbfa976b -
2026-11-13 12:14:55 +00:00

101 lines
3.3 KiB
Python

import logging
from fastapi import FastAPI, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from sqlalchemy.exc import IntegrityError
from app.core.config import settings
from app.middleware.security_headers import SecurityHeadersMiddleware
from app.routes import auth, enquiries, misc, projects, quotations, services
from app.services.image_processing import THUMBNAILS, WATERMARKED, ensure_upload_dirs
logger = logging.getLogger("app")
ensure_upload_dirs()
app = FastAPI(
title=settings.APP_NAME,
version="0.1.0",
description=(
"Backend for the Saura Shakti solar company website and admin dashboard.\n\n"
"**Admin endpoints** require `Authorization: Bearer <token>` from `POST /api/auth/login` "
"(use the *Authorize* button)."
),
docs_url="/docs",
redoc_url="/redoc",
openapi_url="/openapi.json",
)
app.add_middleware(SecurityHeadersMiddleware)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origins_list,
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
allow_headers=["Authorization", "Content-Type"],
)
# Only watermarked images and thumbnails are public. Originals are NOT mounted;
# admins fetch them through an authenticated endpoint.
media_root = settings.UPLOAD_DIR
for sub in (WATERMARKED, THUMBNAILS):
app.mount(
f"{settings.MEDIA_URL_PATH}/{sub}",
StaticFiles(directory=media_root / sub),
name=f"media-{sub}",
)
for module_router in (
auth.router,
auth.users_router,
enquiries.public_router,
enquiries.admin_router,
projects.public_router,
projects.admin_router,
projects.images_router,
services.public_router,
services.admin_router,
misc.router,
quotations.router,
):
app.include_router(module_router, prefix=settings.API_PREFIX)
@app.exception_handler(RequestValidationError)
async def validation_error_handler(_: Request, exc: RequestValidationError):
"""Uniform validation errors: {detail: str, errors: [{field, message}]} for the frontend."""
errors = []
for err in exc.errors():
loc = [str(p) for p in err.get("loc", []) if p not in ("body", "query", "path")]
errors.append({"field": ".".join(loc) or None, "message": err.get("msg", "Invalid value")})
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
content={"detail": "Validation failed", "errors": errors},
)
@app.exception_handler(IntegrityError)
async def integrity_error_handler(_: Request, exc: IntegrityError):
logger.warning("Integrity error: %s", exc.orig)
return JSONResponse(
status_code=status.HTTP_409_CONFLICT,
content={"detail": "The request conflicts with existing data."},
)
@app.exception_handler(Exception)
async def unhandled_error_handler(_: Request, exc: Exception):
logger.exception("Unhandled error", exc_info=exc)
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={"detail": "Something went wrong. Please try again."},
)
@app.get("/", include_in_schema=False)
async def root():
return {"name": settings.APP_NAME, "docs": "/docs", "health": f"{settings.API_PREFIX}/health"}