27 lines
1.0 KiB
Python
Raw Normal View History

2023-10-12 23:01:51 +02:00
from datetime import datetime, timedelta
2023-10-12 00:04:18 +02:00
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, status, APIRouter
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
2023-10-14 17:34:34 +02:00
from ..dependencies import users_token
2023-10-12 00:04:18 +02:00
from ..models import token
router = APIRouter()
2023-10-13 17:54:46 +02:00
ACCESS_TOKEN_EXPIRE_MINUTES = 30
2023-10-12 00:04:18 +02:00
@router.post("/token", response_model=token.Token, tags=["token"])
async def login_for_access_token(
form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
):
2023-10-14 17:34:34 +02:00
user = users_token.authenticate_user(form_data.username, form_data.password)
2023-10-12 00:04:18 +02:00
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
2023-10-13 17:54:46 +02:00
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
2023-10-14 17:34:34 +02:00
access_token = users_token.create_access_token(
2023-10-12 00:04:18 +02:00
data={"sub": user.username}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}