Spaces:
Sleeping
Sleeping
Add auth router
Browse files- app/routers/auth.py +40 -0
app/routers/auth.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Authentication routes: register and login."""
|
| 2 |
+
from fastapi import APIRouter, Depends, HTTPException
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
from sqlalchemy.orm import Session
|
| 5 |
+
|
| 6 |
+
from .. import models, schemas, security
|
| 7 |
+
from ..database import get_db
|
| 8 |
+
|
| 9 |
+
router = APIRouter(prefix="/auth", tags=["auth"])
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class LoginRequest(BaseModel):
|
| 13 |
+
username: str
|
| 14 |
+
password: str
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@router.post("/register", response_model=schemas.Token, status_code=201)
|
| 18 |
+
def register(body: schemas.UserCreate, db: Session = Depends(get_db)):
|
| 19 |
+
if db.query(models.User).filter(models.User.username == body.username).first():
|
| 20 |
+
raise HTTPException(409, "Username already taken")
|
| 21 |
+
if db.query(models.User).filter(models.User.email == body.email).first():
|
| 22 |
+
raise HTTPException(409, "Email already registered")
|
| 23 |
+
|
| 24 |
+
user = models.User(
|
| 25 |
+
username=body.username,
|
| 26 |
+
email=body.email,
|
| 27 |
+
hashed_password=security.hash_password(body.password),
|
| 28 |
+
)
|
| 29 |
+
db.add(user)
|
| 30 |
+
db.commit()
|
| 31 |
+
db.refresh(user)
|
| 32 |
+
return schemas.Token(access_token=security.create_access_token(user.id), user=user)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@router.post("/login", response_model=schemas.Token)
|
| 36 |
+
def login(body: LoginRequest, db: Session = Depends(get_db)):
|
| 37 |
+
user = db.query(models.User).filter(models.User.username == body.username).first()
|
| 38 |
+
if user is None or not security.verify_password(body.password, user.hashed_password):
|
| 39 |
+
raise HTTPException(401, "Invalid username or password")
|
| 40 |
+
return schemas.Token(access_token=security.create_access_token(user.id), user=user)
|