-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathmain.py
More file actions
113 lines (100 loc) · 4.01 KB
/
main.py
File metadata and controls
113 lines (100 loc) · 4.01 KB
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
110
111
112
113
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import Response
from contextlib import asynccontextmanager
from app.database import connect_to_mongo, close_mongo_connection
from app.auth.routes import router as auth_router
from app.user.routes import router as user_router
from app.config import settings
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup
print("Lifespan: Connecting to MongoDB...")
await connect_to_mongo()
print("Lifespan: MongoDB connected.")
yield
# Shutdown
print("Lifespan: Closing MongoDB connection...")
await close_mongo_connection()
print("Lifespan: MongoDB connection closed.")
app = FastAPI(
title="Splitwiser API",
description="Backend API for Splitwiser expense tracking application",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc",
lifespan=lifespan
)
# CORS middleware - Enhanced configuration for production
allowed_origins = []
if settings.allow_all_origins:
# Allow all origins in development mode
allowed_origins = ["*"]
print("Development mode: CORS configured to allow all origins")
elif settings.allowed_origins:
# Use specified origins in production mode
allowed_origins = [origin.strip() for origin in settings.allowed_origins.split(",") if origin.strip()]
else:
# Fallback to allow all origins if not specified (not recommended for production)
allowed_origins = ["*"]
print(f"Allowed CORS origins: {allowed_origins}")
app.add_middleware(
CORSMiddleware,
allow_origins=allowed_origins,
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH"],
allow_headers=[
"Accept",
"Accept-Language",
"Content-Language",
"Content-Type",
"Authorization",
"X-Requested-With",
"Origin",
"Cache-Control",
"Pragma",
"X-CSRFToken"
],
expose_headers=["*"],
max_age=3600, # Cache preflight responses for 1 hour
)
# Add a catch-all OPTIONS handler that should work for any path
@app.options("/{path:path}")
async def options_handler(request: Request, path: str):
"""Handle all OPTIONS requests"""
print(f"OPTIONS request received for path: /{path}")
print(f"Origin: {request.headers.get('origin', 'No origin header')}")
response = Response(status_code=200)
# Manually set CORS headers for debugging
origin = request.headers.get("origin")
if origin and (origin in allowed_origins or "*" in allowed_origins):
response.headers["Access-Control-Allow-Origin"] = origin
response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH"
response.headers["Access-Control-Allow-Headers"] = "Accept, Accept-Language, Content-Language, Content-Type, Authorization, X-Requested-With, Origin, Cache-Control, Pragma, X-CSRFToken"
response.headers["Access-Control-Allow-Credentials"] = "true"
response.headers["Access-Control-Max-Age"] = "3600"
elif "*" in allowed_origins:
response.headers["Access-Control-Allow-Origin"] = "*"
response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH"
response.headers["Access-Control-Allow-Headers"] = "Accept, Accept-Language, Content-Language, Content-Type, Authorization, X-Requested-With, Origin, Cache-Control, Pragma, X-CSRFToken"
response.headers["Access-Control-Max-Age"] = "3600"
return response
# Health check
@app.get("/health")
async def health_check():
"""
Returns the health status of the Splitwiser API service.
This endpoint can be used for health checks and monitoring.
"""
return {"status": "healthy", "service": "Splitwiser API"}
# Include routers
app.include_router(auth_router)
app.include_router(user_router)
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"main:app",
host="0.0.0.0",
port=8000,
reload=settings.debug
)