PhotosAPI/extensions/security.py

29 lines
960 B
Python
Raw Normal View History

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