Update code in endpoints/login.post.py

This commit is contained in:
Backend IM Bot 2025-03-29 19:34:06 +00:00
parent 2b0ac8979f
commit 0c0d8dd2a6

View File

@ -1,37 +1,23 @@
from fastapi import APIRouter, Depends, HTTPException from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from datetime import timedelta
from core.database import get_db
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from core.auth import verify_password, create_access_token from typing import List
from core.database import get_db
from models.user import User from models.user import User
from schemas.user import UserSchema, UserCreate, UserLogin
from helpers.user_helpers import authenticate_user
router = APIRouter() router = APIRouter()
class UserAuth(BaseModel): @router.post("/login", status_code=200, response_model=UserSchema)
username: str
password: str
@router.post("/login")
async def login( async def login(
user_data: UserAuth, user_data: UserLogin,
db: Session = Depends(get_db) db: Session = Depends(get_db)
): ):
"""User authentication endpoint""" user = authenticate_user(db, user_data.email, user_data.password)
user = db.query(User).filter(User.username == user_data.username).first() if not user:
raise HTTPException(
if not user or not verify_password(user_data.password, user.hashed_password): status_code=status.HTTP_401_UNAUTHORIZED,
raise HTTPException(status_code=400, detail="Invalid credentials") detail="Incorrect email or password",
headers={"WWW-Authenticate": "Bearer"},
# Generate token with expiration
access_token = create_access_token(
data={"sub": user.id},
expires_delta=timedelta(hours=1)
) )
return user
return {
"access_token": access_token,
"token_type": "bearer",
"user_id": user.id,
"username": user.username
}