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 ..auth import (
|
|
|
|
authenticate_user,
|
|
|
|
create_access_token,
|
|
|
|
create_refresh_token,
|
|
|
|
verify_refresh_token,
|
|
|
|
)
|
2024-08-04 16:17:16 +02:00
|
|
|
from ..domain.user import User as DBUser
|
|
|
|
from ..model.token import RefreshTokenPayload, Token
|
|
|
|
from .base import BaseController
|
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)
|
2024-05-21 15:18:03 +02:00
|
|
|
|
|
|
|
if user is None:
|
|
|
|
raise HTTPException(status_code=401, detail="Invalid token")
|
|
|
|
|
|
|
|
assert user is not None
|
2023-04-02 15:20:53 +02:00
|
|
|
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",
|
|
|
|
)
|