PhotosAPI/extensions/security.py

31 lines
963 B
Python
Raw Normal View History

2023-01-09 16:01:30 +02:00
from datetime import timedelta
2023-02-16 15:55:03 +02:00
from classes.exceptions import UserCredentialsInvalid
2022-12-20 12:36:54 +02:00
from modules.app import app
2023-02-16 15:56:28 +02:00
from fastapi import Depends
2022-12-20 12:36:54 +02:00
from fastapi.security import (
OAuth2PasswordRequestForm,
)
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()):
user = authenticate_user(form_data.username, form_data.password)
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"}