File size: 3,255 Bytes
351e71f
f40c733
 
 
 
 
e2540a4
f40c733
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
307ec43
e2540a4
 
307ec43
 
 
 
 
 
 
e2540a4
f40c733
 
 
351e71f
 
 
 
 
 
 
 
f40c733
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import os
from contextlib import asynccontextmanager
from typing import AsyncGenerator

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware.trustedhost import TrustedHostMiddleware

from .routes.tasks import router as tasks_router
from .routes.auth import router as auth_router
from ..config import settings
from ..utils.error_handlers import add_exception_handlers
from ..middleware.security import SecurityHeadersMiddleware
from sqlmodel import SQLModel
from ..database.database import sync_engine
from ..models.user import User
from ..models.task import Task


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
    """
    Lifespan event handler for FastAPI application.

    Handles startup and shutdown events.
    """
    # Startup

    # Create database tables
    SQLModel.metadata.create_all(bind=sync_engine)

    # Add exception handlers
    add_exception_handlers(app)

    yield

    # Shutdown


def create_app() -> FastAPI:
    """
    Create and configure the FastAPI application.

    Returns:
        Configured FastAPI application instance
    """
    app = FastAPI(
        title=settings.app_name,
        debug=settings.debug,
        lifespan=lifespan
    )

    # Add security headers middleware first
    app.add_middleware(SecurityHeadersMiddleware)

    # Add custom middleware to handle HTTPS redirects properly in proxy environments like Hugging Face Spaces
    # This handles forwarded headers (X-Forwarded-Proto, X-Forwarded-Host, etc.)
    # which is essential when running behind a proxy/load balancer like Hugging Face
    @app.middleware("http")
    async def https_redirect_middleware(request, call_next):
        # Handle X-Forwarded-Proto header to preserve HTTPS when behind proxy/load balancer
        if request.headers.get("x-forwarded-proto") == "https":
            request.scope["scheme"] = "https"
        response = await call_next(request)
        return response

    # Add CORS middleware
    app.add_middleware(
        CORSMiddleware,
        allow_origins=[
            "https://frontend-hugging.vercel.app",
            "https://frontend-hugging-myidyjvtn-asma-akbar-raos-projects.vercel.app",  # Current Vercel deployment URL
            "https://asmaakbar-phase-ll.hf.space",  # Hugging Face Space URL
            "http://localhost:3000",  # For local development
            "http://localhost:8000",  # For local backend
            settings.frontend_url,  # Use configured frontend URL from settings
        ],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # Include API routes
    app.include_router(tasks_router, prefix=settings.api_prefix)
    app.include_router(auth_router, prefix=settings.api_prefix)

    @app.get("/")
    async def root():
        """Root endpoint for the API."""
        return {
            "message": "Welcome to the Todo Backend API",
            "app_name": settings.app_name,
            "version": "1.0.0"
        }

    return app


app = create_app()

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "backend.src.api.main:app",
        host="0.0.0.0",
        port=8000,
        reload=True
    )