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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -28
app.py CHANGED
@@ -1,6 +1,6 @@
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
@@ -8,63 +8,62 @@ 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
39
 
40
  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_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):
59
  email = data.email.lower().strip()
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"}
 
1
+ from fastapi import FastAPI, HTTPException, status, Request
2
  from fastapi.middleware.cors import CORSMiddleware
3
+ from pydantic import BaseModel, EmailStr, constr
4
  import hashlib
5
  import os
6
  import certifi
 
8
 
9
  app = FastAPI()
10
 
11
+ # === CORS Configuration ===
12
  app.add_middleware(
13
  CORSMiddleware,
14
+ allow_origins=["*"], # In production, replace with specific domains
15
  allow_credentials=True,
16
+ allow_methods=["POST", "GET"],
17
+ allow_headers=["Authorization", "Content-Type"],
18
  )
19
 
20
+ # === Secure MongoDB Setup ===
21
  MONGO_URI = os.getenv("MONGO_URI")
 
22
  if not MONGO_URI:
23
+ raise RuntimeError("Missing MONGO_URI in environment")
24
 
 
25
  client = AsyncIOMotorClient(MONGO_URI, tls=True, tlsCAFile=certifi.where())
26
  db = client["cps_db"]
27
+ users_collection = db.get_collection("users")
28
 
29
+ # === Utility: Strong Hashing ===
30
  def hash_password(password: str) -> str:
31
  return hashlib.sha256(password.encode()).hexdigest()
32
 
33
+ # === Pydantic Models with Validation ===
34
  class SignupForm(BaseModel):
35
+ email: EmailStr
36
+ password: constr(min_length=8)
37
 
38
  class LoginForm(BaseModel):
39
+ email: EmailStr
40
  password: str
41
 
42
+ # === Signup Endpoint ===
43
+ @app.post("/signup", status_code=status.HTTP_201_CREATED)
44
  async def signup(data: SignupForm):
45
  email = data.email.lower().strip()
46
+ hashed_password = hash_password(data.password)
47
 
48
+ if await users_collection.find_one({"email": email}):
 
49
  raise HTTPException(status_code=409, detail="Email already registered")
50
 
51
+ await users_collection.insert_one({"email": email, "password": hashed_password})
52
+ return {"success": True, "message": "Account created successfully"}
53
 
54
+ # === Login Endpoint ===
55
  @app.post("/login")
56
  async def login(data: LoginForm):
57
  email = data.email.lower().strip()
58
+ hashed_password = hash_password(data.password)
59
 
60
+ user = await users_collection.find_one({"email": email, "password": hashed_password})
61
  if not user:
62
+ raise HTTPException(status_code=401, detail="Invalid email or password")
63
 
64
  return {"success": True, "message": "Login successful"}
65
 
66
+ # === Health Check ===
67
  @app.get("/")
68
+ async def root():
69
+ return {"message": "✅ FastAPI MongoDB Auth API is live"}