Add POST endpoint for /login

This commit is contained in:
Backend IM Bot 2025-03-28 04:36:05 +00:00
parent ee15dcc594
commit 18ea09a987

View File

@ -1,33 +1,34 @@
# Entity: User # Entity: User
```python
from fastapi import APIRouter, Depends, HTTPException, status from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from core.database import get_db from core.database import get_db
from models.user import User from models.user import User
from schemas.user import UserSchema, UserLogin from schemas.user import UserSchema, UserLogin, UserResponse
from helpers.user_helpers import authenticate_user, create_access_token from helpers.user_helpers import authenticate_user, create_access_token
from core.security import create_access_token from core.security import verify_password
router = APIRouter() router = APIRouter()
@router.post("/login", status_code=200) @router.post("/login", response_model=UserResponse, status_code=status.HTTP_200_OK)
async def login( async def login(
login_data: UserLogin, user_credentials: UserLogin,
db: Session = Depends(get_db) db: Session = Depends(get_db)
): ):
"""Authenticate user and return access token""" user = authenticate_user(db, user_credentials.email, user_credentials.password)
user = authenticate_user(db, login_data.username, login_data.password)
if not user: if not user:
raise HTTPException( raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password", detail="Incorrect email or password",
headers={"WWW-Authenticate": "Bearer"}, headers={"WWW-Authenticate": "Bearer"},
) )
access_token = create_access_token(data={"sub": user.username}) access_token = create_access_token(data={"sub": user.email})
return { return {
"access_token": access_token, "access_token": access_token,
"token_type": "bearer", "token_type": "bearer",
"user": UserSchema.from_orm(user) "user": user
} }
```