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-18 23:59:18 +02:00
|
|
|
from ..dependencies import users_token, permissions_checker
|
|
|
|
from ..models import token, users
|
2023-10-12 00:04:18 +02:00
|
|
|
|
|
|
|
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)
|
2023-10-20 22:26:48 +02:00
|
|
|
response.set_cookie(key="access_token", value="Bearer {0}".format(access_token), httponly=True)
|
2023-10-18 23:59:18 +02:00
|
|
|
return response
|
|
|
|
|
|
|
|
@router.get("/token",tags=["token"])
|
|
|
|
async def check_token(current_user: Annotated[users.User, Depends(users_token.get_current_active_user)], authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))]):
|
|
|
|
content = {"message": "Check token"}
|
|
|
|
response = JSONResponse(content=content)
|
2023-10-20 22:43:59 +02:00
|
|
|
return response
|
|
|
|
|
|
|
|
@router.delete("/token",tags=["token"])
|
|
|
|
async def check_token(current_user: Annotated[users.User, Depends(users_token.get_current_active_user)], authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))]):
|
|
|
|
content = {"message": "Token deleted"}
|
|
|
|
response = JSONResponse(content=content)
|
|
|
|
response.set_cookie(key="access_token", value="", httponly=True)
|
2023-10-18 23:59:18 +02:00
|
|
|
return response
|