From 90f5d1bacbe23b0f33027ce58e7b5f4e4e7c3ab9 Mon Sep 17 00:00:00 2001 From: Backend IM Bot Date: Tue, 11 Mar 2025 11:09:26 +0000 Subject: [PATCH] feat: Update endpoint login --- app/api/endpoints/login.py | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/app/api/endpoints/login.py b/app/api/endpoints/login.py index 6ed4dac..01e9fc6 100644 --- a/app/api/endpoints/login.py +++ b/app/api/endpoints/login.py @@ -1,7 +1,28 @@ -from fastapi import APIRouter +from fastapi import APIRouter, Depends, HTTPException, status +from fastapi.security import OAuth2PasswordRequestForm +from sqlalchemy.orm import Session +from typing import Optional + +from models import User +from database import get_db +from auth import authenticate_user, create_access_token router = APIRouter() @router.post("/login") -async def login(username: str, password: str): - return {"message": "User logged in successfully", "username": username} \ No newline at end of file +async def login( + form_data: OAuth2PasswordRequestForm = Depends(), + db: Session = Depends(get_db), +): + """ + Authenticate user and return access token + """ + user = authenticate_user(db, form_data.username, form_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"} \ No newline at end of file