2023-01-09 16:01:30 +02:00
|
|
|
from datetime import timedelta
|
2022-12-20 12:36:54 +02:00
|
|
|
|
2023-02-16 15:56:28 +02:00
|
|
|
from fastapi import Depends
|
2023-06-22 14:17:53 +03:00
|
|
|
from fastapi.security import OAuth2PasswordRequestForm
|
2022-12-20 12:36:54 +02:00
|
|
|
|
2023-06-22 14:17:53 +03:00
|
|
|
from classes.exceptions import UserCredentialsInvalid
|
|
|
|
from modules.app import app
|
2022-12-20 12:36:54 +02:00
|
|
|
from modules.security import (
|
|
|
|
ACCESS_TOKEN_EXPIRE_DAYS,
|
|
|
|
Token,
|
|
|
|
authenticate_user,
|
2023-03-12 15:59:13 +02:00
|
|
|
create_access_token,
|
2022-12-20 12:36:54 +02:00
|
|
|
)
|
|
|
|
|
2023-03-12 15:59:13 +02:00
|
|
|
token_post_responses = {401: UserCredentialsInvalid().openapi}
|
|
|
|
|
|
|
|
|
2023-02-16 15:55:03 +02:00
|
|
|
@app.post("/token", response_model=Token, responses=token_post_responses)
|
2022-12-20 12:36:54 +02:00
|
|
|
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
|
2023-08-14 14:44:07 +03:00
|
|
|
user = await authenticate_user(form_data.username, form_data.password)
|
2022-12-20 12:36:54 +02:00
|
|
|
if not user:
|
2023-02-16 15:55:03 +02:00
|
|
|
raise UserCredentialsInvalid()
|
2022-12-20 12:36:54 +02:00
|
|
|
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,
|
|
|
|
)
|
2023-03-12 15:59:13 +02:00
|
|
|
return {"access_token": access_token, "token_type": "bearer"}
|