bsition/bsition/api/endpoints/token.py

28 lines
829 B
Python

from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import JSONResponse
from fastapi.security import OAuth2PasswordRequestForm
from bsition.api.utils.jwt import write_token
from bsition.api.utils.password import verify_password
from bsition.backend.postgres.users import get_user_by_username
router = APIRouter()
@router.post("/token")
def login(form: OAuth2PasswordRequestForm = Depends()):
user = get_user_by_username(form.username)
if user is None or not verify_password(form.password, user[2]):
raise HTTPException(
status_code=400,
detail="User not found.",
)
return JSONResponse(
content={
"access_token": write_token({"sub": form.username}),
"token_type": "bearer",
},
status_code=202,
)