29 lines
959 B
Python
29 lines
959 B
Python
from fastapi import APIRouter, Depends, HTTPException
|
|
from fastapi.security import OAuth2PasswordRequestForm
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
import services.users as user_service
|
|
from core.security import verify_password
|
|
from jose import jwt
|
|
from datetime import datetime, UTC, timedelta
|
|
from core.settings import JWT_SECRET
|
|
from db.session import get_db
|
|
|
|
|
|
router = APIRouter(prefix="/auth", tags=["auth"])
|
|
|
|
|
|
@router.post("/login")
|
|
async def login(form_data: OAuth2PasswordRequestForm = Depends(), db: AsyncSession = Depends(get_db)):
|
|
|
|
user = await user_service.find_user_by_email(form_data.username, db)
|
|
|
|
if not user or not verify_password(form_data.password, user.password):
|
|
raise HTTPException(401, "Incorrect email or password")
|
|
|
|
token = jwt.encode(
|
|
{"sub": f"{user.id}", "exp": datetime.now(UTC) + timedelta(minutes=30)},
|
|
JWT_SECRET,
|
|
algorithm="HS256"
|
|
)
|
|
|
|
return {"access_token": token}
|