2025-03-29 09:52:02 +00:00

24 lines
913 B
Python

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from core.database import get_db
from models.user import User
from schemas.user import UserLogin, UserResponse
from helpers.user_helpers import authenticate_user, create_access_token
router = APIRouter()
@router.post("/login", status_code=200, response_model=UserResponse)
async def login(
user_credentials: UserLogin,
db: Session = Depends(get_db)
):
user = authenticate_user(db, user_credentials.username, user_credentials.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token = create_access_token(data={"sub": user.username})
return {"access_token": access_token, "token_type": "bearer", "user": user}