from datetime import timedelta from fastapi import Depends from fastapi.security import OAuth2PasswordRequestForm from classes.exceptions import UserCredentialsInvalid from modules.app import app from modules.security import ( ACCESS_TOKEN_EXPIRE_DAYS, Token, authenticate_user, create_access_token, ) token_post_responses = {401: UserCredentialsInvalid().openapi} @app.post("/token", response_model=Token, responses=token_post_responses) async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): user = authenticate_user(form_data.username, form_data.password) if not user: raise UserCredentialsInvalid() access_token_expires = timedelta(days=ACCESS_TOKEN_EXPIRE_DAYS) access_token = create_access_token( data={"sub": user.user, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) return {"access_token": access_token, "token_type": "bearer"}