Ali2206 commited on
Commit
f2c63f5
·
verified ·
1 Parent(s): 23bcd24

Create api/routes.py

Browse files
Files changed (1) hide show
  1. api/routes.py +34 -0
api/routes.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, HTTPException, Depends
2
+ from fastapi.security import OAuth2PasswordRequestForm
3
+ from app.models.schemas import SignupForm, TokenResponse
4
+ from app.db.mongo import users_collection
5
+ from app.core.security import hash_password, verify_password, create_access_token
6
+ from datetime import datetime
7
+
8
+ router = APIRouter()
9
+
10
+ @router.post("/signup")
11
+ async def signup(data: SignupForm):
12
+ email = data.email.lower().strip()
13
+ existing = await users_collection.find_one({"email": email})
14
+ if existing:
15
+ raise HTTPException(status_code=409, detail="Email already exists")
16
+
17
+ hashed_pw = hash_password(data.password)
18
+ user_doc = {
19
+ "email": email,
20
+ "password": hashed_pw,
21
+ "created_at": datetime.utcnow()
22
+ }
23
+ await users_collection.insert_one(user_doc)
24
+ return {"success": True, "message": "Account created"}
25
+
26
+ @router.post("/login", response_model=TokenResponse)
27
+ async def login(form_data: OAuth2PasswordRequestForm = Depends()):
28
+ email = form_data.username.lower().strip()
29
+ user = await users_collection.find_one({"email": email})
30
+ if not user or not verify_password(form_data.password, user["password"]):
31
+ raise HTTPException(status_code=401, detail="Invalid credentials")
32
+
33
+ access_token = create_access_token(data={"sub": user["email"]})
34
+ return {"access_token": access_token, "token_type": "bearer"}