Ali2206 commited on
Commit
ea97f25
·
verified ·
1 Parent(s): 3198214

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -8
app.py CHANGED
@@ -3,14 +3,15 @@ from fastapi.middleware.cors import CORSMiddleware
3
  from pydantic import BaseModel
4
  import os
5
  import hashlib
6
- import motor.motor_asyncio
 
7
 
8
  app = FastAPI()
9
 
10
- # === CORS ===
11
  app.add_middleware(
12
  CORSMiddleware,
13
- allow_origins=["*"], # Open CORS (limit for prod)
14
  allow_credentials=True,
15
  allow_methods=["*"],
16
  allow_headers=["*"],
@@ -18,15 +19,18 @@ app.add_middleware(
18
 
19
  # === MongoDB Setup ===
20
  MONGO_URI = os.getenv("MONGO_URI")
21
- client = motor.motor_asyncio.AsyncIOMotorClient(MONGO_URI)
22
- db = client["cps_db"] # database name
 
 
 
23
  users_collection = db["users"]
24
 
25
- # === Utils ===
26
  def hash_password(password: str) -> str:
27
  return hashlib.sha256(password.encode()).hexdigest()
28
 
29
- # === Models ===
30
  class SignupForm(BaseModel):
31
  email: str
32
  password: str
@@ -61,4 +65,4 @@ async def login(data: LoginForm):
61
 
62
  @app.get("/")
63
  def root():
64
- return {"message": "MongoDB FastAPI is running ✅"}
 
3
  from pydantic import BaseModel
4
  import os
5
  import hashlib
6
+ import certifi
7
+ from motor.motor_asyncio import AsyncIOMotorClient
8
 
9
  app = FastAPI()
10
 
11
+ # === CORS Middleware ===
12
  app.add_middleware(
13
  CORSMiddleware,
14
+ allow_origins=["*"], # ⚠️ Restrict in production
15
  allow_credentials=True,
16
  allow_methods=["*"],
17
  allow_headers=["*"],
 
19
 
20
  # === MongoDB Setup ===
21
  MONGO_URI = os.getenv("MONGO_URI")
22
+ if not MONGO_URI:
23
+ raise RuntimeError("Missing MONGO_URI environment variable")
24
+
25
+ client = AsyncIOMotorClient(MONGO_URI, tls=True, tlsCAFile=certifi.where())
26
+ db = client["cps_db"]
27
  users_collection = db["users"]
28
 
29
+ # === Password Hashing ===
30
  def hash_password(password: str) -> str:
31
  return hashlib.sha256(password.encode()).hexdigest()
32
 
33
+ # === Pydantic Models ===
34
  class SignupForm(BaseModel):
35
  email: str
36
  password: str
 
65
 
66
  @app.get("/")
67
  def root():
68
+ return {"message": "🚀 MongoDB FastAPI backend is live"}