Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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 |
-
#
|
| 12 |
app.add_middleware(
|
| 13 |
CORSMiddleware,
|
| 14 |
-
allow_origins=["*"], #
|
| 15 |
allow_credentials=True,
|
| 16 |
-
allow_methods=["
|
| 17 |
-
allow_headers=["
|
| 18 |
)
|
| 19 |
|
| 20 |
-
# Secure
|
| 21 |
MONGO_URI = os.getenv("MONGO_URI")
|
| 22 |
-
|
| 23 |
if not MONGO_URI:
|
| 24 |
-
raise RuntimeError("MONGO_URI environment
|
| 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
|
| 30 |
|
| 31 |
-
#
|
| 32 |
def hash_password(password: str) -> str:
|
| 33 |
return hashlib.sha256(password.encode()).hexdigest()
|
| 34 |
|
| 35 |
-
# Pydantic
|
| 36 |
class SignupForm(BaseModel):
|
| 37 |
-
email:
|
| 38 |
-
password:
|
| 39 |
|
| 40 |
class LoginForm(BaseModel):
|
| 41 |
-
email:
|
| 42 |
password: str
|
| 43 |
|
| 44 |
-
#
|
| 45 |
-
@app.post("/signup")
|
| 46 |
async def signup(data: SignupForm):
|
| 47 |
email = data.email.lower().strip()
|
| 48 |
-
|
| 49 |
|
| 50 |
-
|
| 51 |
-
if existing_user:
|
| 52 |
raise HTTPException(status_code=409, detail="Email already registered")
|
| 53 |
|
| 54 |
-
await users_collection.insert_one({"email": email, "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 |
-
|
| 61 |
|
| 62 |
-
user = await users_collection.find_one({"email": email, "password":
|
| 63 |
if not user:
|
| 64 |
-
raise HTTPException(status_code=401, detail="Invalid
|
| 65 |
|
| 66 |
return {"success": True, "message": "Login successful"}
|
| 67 |
|
|
|
|
| 68 |
@app.get("/")
|
| 69 |
-
def root():
|
| 70 |
-
return {"message": "✅ FastAPI MongoDB
|
|
|
|
| 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"}
|