Ali2206 commited on
Commit
d5cea3e
·
verified ·
1 Parent(s): a44cf7a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -17
app.py CHANGED
@@ -1,38 +1,38 @@
1
  from fastapi import FastAPI, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
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 setup ===
12
  app.add_middleware(
13
  CORSMiddleware,
14
- allow_origins=["*"], # Open CORS (adjust for production)
15
  allow_credentials=True,
16
  allow_methods=["*"],
17
  allow_headers=["*"],
18
  )
19
 
20
- # === MongoDB Atlas Setup ===
21
- MONGO_URI = os.getenv("MONGO_URI") # Make sure this is set in HF Secrets
22
 
23
  if not MONGO_URI:
24
- raise RuntimeError("MONGO_URI not set in environment variables!")
25
 
26
- # Use certifi for secure SSL connection
27
  client = AsyncIOMotorClient(MONGO_URI, tls=True, tlsCAFile=certifi.where())
28
  db = client["cps_db"]
29
  users_collection = db["users"]
30
 
31
- # === Utils ===
32
  def hash_password(password: str) -> str:
33
  return hashlib.sha256(password.encode()).hexdigest()
34
 
35
- # === Models ===
36
  class SignupForm(BaseModel):
37
  email: str
38
  password: str
@@ -41,18 +41,18 @@ class LoginForm(BaseModel):
41
  email: str
42
  password: str
43
 
44
- # === Routes ===
45
  @app.post("/signup")
46
  async def signup(data: SignupForm):
47
  email = data.email.lower().strip()
48
  password = hash_password(data.password)
49
 
50
- existing = await users_collection.find_one({"email": email})
51
- if existing:
52
  raise HTTPException(status_code=409, detail="Email already registered")
53
 
54
  await users_collection.insert_one({"email": email, "password": password})
55
- return {"success": True, "message": "Account created successfully"}
56
 
57
  @app.post("/login")
58
  async def login(data: LoginForm):
@@ -60,11 +60,11 @@ async def login(data: LoginForm):
60
  password = hash_password(data.password)
61
 
62
  user = await users_collection.find_one({"email": email, "password": password})
63
- if user:
64
- return {"success": True, "message": "Login successful"}
65
- else:
66
  raise HTTPException(status_code=401, detail="Invalid credentials")
67
 
 
 
68
  @app.get("/")
69
  def root():
70
- return {"message": "✅ MongoDB FastAPI backend is up"}
 
1
  from fastapi import FastAPI, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from pydantic import BaseModel
 
4
  import hashlib
5
+ import os
6
  import certifi
7
  from motor.motor_asyncio import AsyncIOMotorClient
8
 
9
  app = FastAPI()
10
 
11
+ # Allow frontend CORS
12
  app.add_middleware(
13
  CORSMiddleware,
14
+ allow_origins=["*"], # Change to your frontend origin in prod
15
  allow_credentials=True,
16
  allow_methods=["*"],
17
  allow_headers=["*"],
18
  )
19
 
20
+ # Secure Mongo URI from Hugging Face Secrets
21
+ MONGO_URI = os.getenv("MONGO_URI")
22
 
23
  if not MONGO_URI:
24
+ raise RuntimeError("MONGO_URI environment variable is not set!")
25
 
26
+ # Secure SSL connection with certifi
27
  client = AsyncIOMotorClient(MONGO_URI, tls=True, tlsCAFile=certifi.where())
28
  db = client["cps_db"]
29
  users_collection = db["users"]
30
 
31
+ # Password hashing
32
  def hash_password(password: str) -> str:
33
  return hashlib.sha256(password.encode()).hexdigest()
34
 
35
+ # Pydantic models
36
  class SignupForm(BaseModel):
37
  email: str
38
  password: str
 
41
  email: str
42
  password: str
43
 
44
+ # Routes
45
  @app.post("/signup")
46
  async def signup(data: SignupForm):
47
  email = data.email.lower().strip()
48
  password = hash_password(data.password)
49
 
50
+ existing_user = await users_collection.find_one({"email": email})
51
+ if existing_user:
52
  raise HTTPException(status_code=409, detail="Email already registered")
53
 
54
  await users_collection.insert_one({"email": email, "password": password})
55
+ return {"success": True, "message": "Account created"}
56
 
57
  @app.post("/login")
58
  async def login(data: LoginForm):
 
60
  password = hash_password(data.password)
61
 
62
  user = await users_collection.find_one({"email": email, "password": password})
63
+ if not user:
 
 
64
  raise HTTPException(status_code=401, detail="Invalid credentials")
65
 
66
+ return {"success": True, "message": "Login successful"}
67
+
68
  @app.get("/")
69
  def root():
70
+ return {"message": "✅ FastAPI MongoDB backend is running"}