35 lines
1.2 KiB
Python
35 lines
1.2 KiB
Python
|
|
"""Authentication endpoints: login, register, whoami."""
|
||
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||
|
|
|
||
|
|
from .models import UserCreate, UserLogin, Token, UserOut
|
||
|
|
from .service import authenticate_user, create_access_token, create_user
|
||
|
|
from .dependencies import get_current_user
|
||
|
|
|
||
|
|
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||
|
|
|
||
|
|
|
||
|
|
@router.post("/login", response_model=Token)
|
||
|
|
async def login(body: UserLogin):
|
||
|
|
if not authenticate_user(body.username, body.password):
|
||
|
|
raise HTTPException(
|
||
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||
|
|
detail="Incorrect username or password",
|
||
|
|
)
|
||
|
|
token = create_access_token({"sub": body.username})
|
||
|
|
return Token(access_token=token)
|
||
|
|
|
||
|
|
|
||
|
|
@router.post("/register", response_model=UserOut, status_code=status.HTTP_201_CREATED)
|
||
|
|
async def register(body: UserCreate):
|
||
|
|
if not create_user(body.username, body.password):
|
||
|
|
raise HTTPException(
|
||
|
|
status_code=status.HTTP_409_CONFLICT,
|
||
|
|
detail="Username already exists",
|
||
|
|
)
|
||
|
|
return UserOut(username=body.username)
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/me", response_model=UserOut)
|
||
|
|
async def me(username: str = Depends(get_current_user)):
|
||
|
|
return UserOut(username=username)
|