Spaces:
Paused
Paused
Create auth.py
Browse files
auth.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, HTTPException, Depends
|
| 2 |
+
from sqlalchemy.orm import Session
|
| 3 |
+
from passlib.context import CryptContext
|
| 4 |
+
from app.database import SessionLocal
|
| 5 |
+
from app.models import User
|
| 6 |
+
import jwt
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
router = APIRouter()
|
| 10 |
+
SECRET_KEY = "your_secret_key"
|
| 11 |
+
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
| 12 |
+
|
| 13 |
+
def get_db():
|
| 14 |
+
db = SessionLocal()
|
| 15 |
+
try:
|
| 16 |
+
yield db
|
| 17 |
+
finally:
|
| 18 |
+
db.close()
|
| 19 |
+
|
| 20 |
+
@router.post("/register")
|
| 21 |
+
def register(username: str, password: str, db: Session = Depends(get_db)):
|
| 22 |
+
hashed_password = pwd_context.hash(password)
|
| 23 |
+
user = User(username=username, password=hashed_password)
|
| 24 |
+
db.add(user)
|
| 25 |
+
db.commit()
|
| 26 |
+
return {"message": "User registered"}
|
| 27 |
+
|
| 28 |
+
@router.post("/login")
|
| 29 |
+
def login(username: str, password: str, db: Session = Depends(get_db)):
|
| 30 |
+
user = db.query(User).filter(User.username == username).first()
|
| 31 |
+
if not user or not pwd_context.verify(password, user.password):
|
| 32 |
+
raise HTTPException(status_code=401, detail="Invalid credentials")
|
| 33 |
+
|
| 34 |
+
token = jwt.encode({"user_id": user.id}, SECRET_KEY, algorithm="HS256")
|
| 35 |
+
return {"token": token}
|