From 0687dfe3e51d0ee3f2a9b21a021142a3a5f24da5 Mon Sep 17 00:00:00 2001 From: Backend IM Bot Date: Sat, 29 Mar 2025 20:53:19 +0000 Subject: [PATCH] Update code in endpoints/login.post.py --- endpoints/login.post.py | 44 ++++++++++++++--------------------------- 1 file changed, 15 insertions(+), 29 deletions(-) diff --git a/endpoints/login.post.py b/endpoints/login.post.py index a8ab4aa..a63ef50 100644 --- a/endpoints/login.post.py +++ b/endpoints/login.post.py @@ -1,37 +1,23 @@ -from fastapi import APIRouter, Depends, HTTPException -from pydantic import BaseModel -from datetime import timedelta -from core.database import get_db +from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.orm import Session -from core.auth import verify_password, create_access_token +from core.database import get_db from models.user import User +from schemas.user import UserLogin, TokenResponse +from helpers.auth_helpers import authenticate_user, create_access_token router = APIRouter() -class UserAuth(BaseModel): - username: str - password: str - -@router.post("/login") +@router.post("/login", status_code=200, response_model=TokenResponse) async def login( - user_data: UserAuth, + login_data: UserLogin, db: Session = Depends(get_db) ): - """User authentication endpoint""" - user = db.query(User).filter(User.username == user_data.username).first() - - if not user or not verify_password(user_data.password, user.hashed_password): - raise HTTPException(status_code=400, detail="Invalid credentials") - - # Generate token with expiration - access_token = create_access_token( - data={"sub": user.id}, - expires_delta=timedelta(hours=1) - ) - - return { - "access_token": access_token, - "token_type": "bearer", - "user_id": user.id, - "username": user.username - } + user = authenticate_user(db, login_data.email, login_data.password) + if not user: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect email or password", + headers={"WWW-Authenticate": "Bearer"}, + ) + access_token = create_access_token(data={"sub": user.email}) + return {"access_token": access_token, "token_type": "bearer"} \ No newline at end of file