|
| 1 | +import uuid |
| 2 | +from datetime import UTC, datetime, timedelta |
| 3 | +from typing import Any, ClassVar, Self |
| 4 | + |
| 5 | +import jwt |
| 6 | +from fastapi import HTTPException, status |
| 7 | +from pydantic import Field, SecretStr |
| 8 | +from sqlalchemy import Result, Select, select |
| 9 | +from sqlalchemy.exc import NoResultFound |
| 10 | + |
| 11 | +from futuramaapi.core import settings |
| 12 | +from futuramaapi.helpers.pydantic import BaseModel |
| 13 | +from futuramaapi.repositories.models import UserModel |
| 14 | +from futuramaapi.routers.services import BaseSessionService |
| 15 | + |
| 16 | + |
| 17 | +class GetAuthUserTokenResponse(BaseModel): |
| 18 | + access_token: str = Field( |
| 19 | + alias="access_token", |
| 20 | + description="Keep in mind, that the field is not in a camel case. That's the standard.", |
| 21 | + ) |
| 22 | + refresh_token: str = Field( |
| 23 | + alias="refresh_token", |
| 24 | + description="Keep in mind, that the field is not in a camel case. That's the standard.", |
| 25 | + ) |
| 26 | + |
| 27 | + _default_access_seconds: ClassVar[int] = 15 * 60 |
| 28 | + _default_refresh_seconds: ClassVar[int] = 5 * 24 * 60 * 60 |
| 29 | + |
| 30 | + @classmethod |
| 31 | + def from_user_model( |
| 32 | + cls, |
| 33 | + user: UserModel, |
| 34 | + /, |
| 35 | + *, |
| 36 | + algorithm="HS256", |
| 37 | + ) -> Self: |
| 38 | + return cls( |
| 39 | + access_token=jwt.encode( |
| 40 | + { |
| 41 | + "exp": datetime.now(UTC) + timedelta(seconds=cls._default_access_seconds), |
| 42 | + "nonce": uuid.uuid4().hex, |
| 43 | + "type": "access", |
| 44 | + "user": { |
| 45 | + "id": user.id, |
| 46 | + }, |
| 47 | + }, |
| 48 | + settings.secret_key.get_secret_value(), |
| 49 | + algorithm=algorithm, |
| 50 | + ), |
| 51 | + refresh_token=jwt.encode( |
| 52 | + { |
| 53 | + "exp": datetime.now(UTC) + timedelta(seconds=cls._default_refresh_seconds), |
| 54 | + "nonce": uuid.uuid4().hex, |
| 55 | + "type": "refresh", |
| 56 | + "user": { |
| 57 | + "id": user.id, |
| 58 | + }, |
| 59 | + }, |
| 60 | + settings.secret_key.get_secret_value(), |
| 61 | + algorithm=algorithm, |
| 62 | + ), |
| 63 | + ) |
| 64 | + |
| 65 | + |
| 66 | +class GetAuthUserTokenService(BaseSessionService[GetAuthUserTokenResponse]): |
| 67 | + username: str |
| 68 | + password: SecretStr |
| 69 | + |
| 70 | + @property |
| 71 | + def __user_statement(self) -> Select[tuple[UserModel]]: |
| 72 | + return select(UserModel).where(UserModel.username == self.username) |
| 73 | + |
| 74 | + async def _get_user(self) -> UserModel: |
| 75 | + result: Result[tuple[Any]] = await self.session.execute(self.__user_statement) |
| 76 | + try: |
| 77 | + return result.scalars().one() |
| 78 | + except NoResultFound: |
| 79 | + raise HTTPException( |
| 80 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 81 | + ) from None |
| 82 | + |
| 83 | + async def process(self, *args, **kwargs) -> GetAuthUserTokenResponse: |
| 84 | + user: UserModel = await self._get_user() |
| 85 | + if not self.hasher.verify(self.password.get_secret_value(), user.password): |
| 86 | + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED) |
| 87 | + |
| 88 | + return GetAuthUserTokenResponse.from_user_model(user) |
0 commit comments