Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
from fastapi import FastAPI, HTTPException, Depends
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
from fastapi.security import OAuth2PasswordRequestForm
|
| 4 |
-
from pydantic import BaseModel
|
| 5 |
from jose import JWTError, jwt
|
| 6 |
from passlib.context import CryptContext
|
| 7 |
from motor.motor_asyncio import AsyncIOMotorClient
|
|
@@ -9,8 +9,8 @@ import certifi
|
|
| 9 |
import os
|
| 10 |
import datetime
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
SECRET_KEY = os.getenv("SECRET_KEY", "your-secret-key")
|
| 14 |
ALGORITHM = "HS256"
|
| 15 |
ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
| 16 |
|
|
@@ -18,47 +18,47 @@ MONGO_URI = os.getenv("MONGO_URI")
|
|
| 18 |
if not MONGO_URI:
|
| 19 |
raise RuntimeError("MONGO_URI not set")
|
| 20 |
|
| 21 |
-
# MongoDB
|
| 22 |
client = AsyncIOMotorClient(MONGO_URI, tls=True, tlsCAFile=certifi.where())
|
| 23 |
db = client["cps_db"]
|
| 24 |
users_collection = db["users"]
|
| 25 |
|
| 26 |
-
# App setup
|
| 27 |
app = FastAPI()
|
| 28 |
app.add_middleware(
|
| 29 |
CORSMiddleware,
|
| 30 |
-
allow_origins=["*"], #
|
| 31 |
allow_credentials=True,
|
| 32 |
allow_methods=["*"],
|
| 33 |
allow_headers=["*"],
|
| 34 |
)
|
| 35 |
|
| 36 |
-
#
|
| 37 |
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
| 38 |
|
| 39 |
-
def verify_password(plain, hashed):
|
| 40 |
return pwd_context.verify(plain, hashed)
|
| 41 |
|
| 42 |
-
def hash_password(password):
|
| 43 |
return pwd_context.hash(password)
|
| 44 |
|
| 45 |
-
# JWT
|
| 46 |
def create_access_token(data: dict, expires_delta: datetime.timedelta = None):
|
| 47 |
to_encode = data.copy()
|
| 48 |
expire = datetime.datetime.utcnow() + (expires_delta or datetime.timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
|
| 49 |
to_encode.update({"exp": expire})
|
| 50 |
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
| 51 |
|
| 52 |
-
# Schemas
|
| 53 |
class SignupForm(BaseModel):
|
| 54 |
-
email:
|
| 55 |
password: str
|
| 56 |
|
| 57 |
class TokenResponse(BaseModel):
|
| 58 |
access_token: str
|
| 59 |
token_type: str
|
| 60 |
|
| 61 |
-
# Routes
|
| 62 |
@app.post("/signup")
|
| 63 |
async def signup(data: SignupForm):
|
| 64 |
email = data.email.lower().strip()
|
|
@@ -67,11 +67,12 @@ async def signup(data: SignupForm):
|
|
| 67 |
raise HTTPException(status_code=409, detail="Email already exists")
|
| 68 |
hashed_pw = hash_password(data.password)
|
| 69 |
await users_collection.insert_one({"email": email, "password": hashed_pw})
|
| 70 |
-
return {"success": True, "message": "Account created"}
|
| 71 |
|
| 72 |
@app.post("/login", response_model=TokenResponse)
|
| 73 |
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
|
| 74 |
-
|
|
|
|
| 75 |
if not user or not verify_password(form_data.password, user["password"]):
|
| 76 |
raise HTTPException(status_code=401, detail="Invalid credentials")
|
| 77 |
|
|
@@ -80,4 +81,4 @@ async def login(form_data: OAuth2PasswordRequestForm = Depends()):
|
|
| 80 |
|
| 81 |
@app.get("/")
|
| 82 |
def root():
|
| 83 |
-
return {"message": "
|
|
|
|
| 1 |
from fastapi import FastAPI, HTTPException, Depends
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
from fastapi.security import OAuth2PasswordRequestForm
|
| 4 |
+
from pydantic import BaseModel, EmailStr
|
| 5 |
from jose import JWTError, jwt
|
| 6 |
from passlib.context import CryptContext
|
| 7 |
from motor.motor_asyncio import AsyncIOMotorClient
|
|
|
|
| 9 |
import os
|
| 10 |
import datetime
|
| 11 |
|
| 12 |
+
# === Environment and config ===
|
| 13 |
+
SECRET_KEY = os.getenv("SECRET_KEY", "your-secret-key")
|
| 14 |
ALGORITHM = "HS256"
|
| 15 |
ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
| 16 |
|
|
|
|
| 18 |
if not MONGO_URI:
|
| 19 |
raise RuntimeError("MONGO_URI not set")
|
| 20 |
|
| 21 |
+
# === MongoDB client ===
|
| 22 |
client = AsyncIOMotorClient(MONGO_URI, tls=True, tlsCAFile=certifi.where())
|
| 23 |
db = client["cps_db"]
|
| 24 |
users_collection = db["users"]
|
| 25 |
|
| 26 |
+
# === App setup ===
|
| 27 |
app = FastAPI()
|
| 28 |
app.add_middleware(
|
| 29 |
CORSMiddleware,
|
| 30 |
+
allow_origins=["*"], # Replace with frontend origin in prod
|
| 31 |
allow_credentials=True,
|
| 32 |
allow_methods=["*"],
|
| 33 |
allow_headers=["*"],
|
| 34 |
)
|
| 35 |
|
| 36 |
+
# === Password hashing ===
|
| 37 |
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
| 38 |
|
| 39 |
+
def verify_password(plain: str, hashed: str) -> bool:
|
| 40 |
return pwd_context.verify(plain, hashed)
|
| 41 |
|
| 42 |
+
def hash_password(password: str) -> str:
|
| 43 |
return pwd_context.hash(password)
|
| 44 |
|
| 45 |
+
# === JWT ===
|
| 46 |
def create_access_token(data: dict, expires_delta: datetime.timedelta = None):
|
| 47 |
to_encode = data.copy()
|
| 48 |
expire = datetime.datetime.utcnow() + (expires_delta or datetime.timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
|
| 49 |
to_encode.update({"exp": expire})
|
| 50 |
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
| 51 |
|
| 52 |
+
# === Schemas ===
|
| 53 |
class SignupForm(BaseModel):
|
| 54 |
+
email: EmailStr
|
| 55 |
password: str
|
| 56 |
|
| 57 |
class TokenResponse(BaseModel):
|
| 58 |
access_token: str
|
| 59 |
token_type: str
|
| 60 |
|
| 61 |
+
# === Routes ===
|
| 62 |
@app.post("/signup")
|
| 63 |
async def signup(data: SignupForm):
|
| 64 |
email = data.email.lower().strip()
|
|
|
|
| 67 |
raise HTTPException(status_code=409, detail="Email already exists")
|
| 68 |
hashed_pw = hash_password(data.password)
|
| 69 |
await users_collection.insert_one({"email": email, "password": hashed_pw})
|
| 70 |
+
return {"success": True, "message": "Account created successfully"}
|
| 71 |
|
| 72 |
@app.post("/login", response_model=TokenResponse)
|
| 73 |
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
|
| 74 |
+
email = form_data.username.lower().strip()
|
| 75 |
+
user = await users_collection.find_one({"email": email})
|
| 76 |
if not user or not verify_password(form_data.password, user["password"]):
|
| 77 |
raise HTTPException(status_code=401, detail="Invalid credentials")
|
| 78 |
|
|
|
|
| 81 |
|
| 82 |
@app.get("/")
|
| 83 |
def root():
|
| 84 |
+
return {"message": "✅ Auth-secured FastAPI + MongoDB backend is running"}
|