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
|
2023-10-18 22:56:27 +02:00
|
|
|
from fastapi.responses import JSONResponse
|
2023-10-12 00:04:18 +02:00
|
|
|
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
|
|
|
|
2023-10-18 22:56:27 +02:00
|
|
|
@router.post("/token", tags=["token"])
|
2023-10-12 00:04:18 +02:00
|
|
|
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
|
|
|
|
)
|
2023-10-18 22:56:27 +02:00
|
|
|
content = {"message": "Access token generated"}
|
|
|
|
response = JSONResponse(content=content)
|
|
|
|
response.set_cookie(key="jwt", value=access_token)
|
|
|
|
return response
|