2025-03-29 20:54:35 +00:00

28 lines
925 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.auth_helpers import authenticate_user, create_access_token
router = APIRouter()
@router.post("/login", status_code=200, response_model=UserResponse)
async def login(
login_data: UserLogin,
db: Session = Depends(get_db)
):
user = authenticate_user(db, login_data.username, login_data.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
}