2024-05-17 15:23:35 +02:00
|
|
|
from fastapi import HTTPException
|
2023-04-01 16:19:12 +02:00
|
|
|
from fastapi.security import OAuth2PasswordRequestForm
|
|
|
|
|
2023-04-02 14:38:22 +02:00
|
|
|
from ..model.token import Token, RefreshTokenPayload
|
2023-04-01 16:19:12 +02:00
|
|
|
from ..domain.user import User as DBUser
|
2024-05-17 15:23:35 +02:00
|
|
|
from .base import BaseController
|
2023-04-02 14:38:22 +02:00
|
|
|
from ..auth import (
|
|
|
|
authenticate_user,
|
|
|
|
create_access_token,
|
|
|
|
create_refresh_token,
|
|
|
|
verify_refresh_token,
|
|
|
|
)
|
2023-04-01 16:19:12 +02:00
|
|
|
|
|
|
|
|
|
|
|
class CreateToken(BaseController):
|
|
|
|
async def call(self, content: OAuth2PasswordRequestForm) -> Token:
|
2023-04-02 14:38:22 +02:00
|
|
|
async with self.async_session.begin() as session:
|
2023-04-01 16:19:12 +02:00
|
|
|
user = await authenticate_user(session, content.username, content.password)
|
|
|
|
|
|
|
|
if user is None:
|
|
|
|
raise HTTPException(
|
|
|
|
status_code=401, detail="Invalid username or password"
|
|
|
|
)
|
|
|
|
|
2023-04-02 14:38:22 +02:00
|
|
|
refresh_token = await create_refresh_token(session, user)
|
2023-04-01 16:19:12 +02:00
|
|
|
access_token = create_access_token(user)
|
|
|
|
|
|
|
|
return Token(
|
|
|
|
access_token=access_token,
|
2023-04-02 14:38:22 +02:00
|
|
|
refresh_token=refresh_token.token,
|
|
|
|
token_type="bearer",
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
class RefreshToken(BaseController):
|
|
|
|
async def call(self, content: RefreshTokenPayload) -> Token:
|
|
|
|
async with self.async_session.begin() as session:
|
2023-04-02 15:20:53 +02:00
|
|
|
current_token = await verify_refresh_token(session, content.refresh_token)
|
2023-04-02 14:38:22 +02:00
|
|
|
|
2023-04-02 15:20:53 +02:00
|
|
|
if current_token is None:
|
2023-04-02 14:38:22 +02:00
|
|
|
raise HTTPException(status_code=401, detail="Invalid token")
|
|
|
|
|
2023-04-02 15:20:53 +02:00
|
|
|
user = await DBUser.get(session, current_token.user_id)
|
|
|
|
await current_token.delete(session)
|
|
|
|
|
2023-04-02 14:38:22 +02:00
|
|
|
refresh_token = await create_refresh_token(session, user)
|
|
|
|
access_token = create_access_token(user)
|
|
|
|
|
|
|
|
return Token(
|
|
|
|
access_token=access_token,
|
|
|
|
refresh_token=refresh_token.token,
|
2023-04-01 16:19:12 +02:00
|
|
|
token_type="bearer",
|
|
|
|
)
|