24 lines
923 B
Python
24 lines
923 B
Python
from __future__ import annotations
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.database import get_db
|
|
from app.models import User
|
|
from app.schemas import LoginRequest, TokenResponse
|
|
from app.security import create_access_token, verify_password
|
|
from app.serializers import serialize_user
|
|
|
|
|
|
router = APIRouter(prefix="/auth", tags=["auth"])
|
|
|
|
|
|
@router.post("/login", response_model=TokenResponse)
|
|
def login(payload: LoginRequest, db: Session = Depends(get_db)):
|
|
user = db.query(User).filter(User.username == payload.username, User.is_active.is_(True)).first()
|
|
if not user or not verify_password(payload.password, user.password_hash):
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
|
|
token = create_access_token(user.username)
|
|
return TokenResponse(access_token=token, user=serialize_user(user))
|
|
|