47 lines
2.0 KiB
Python
Raw Normal View History

from dataclasses import field
2023-05-01 20:00:32 +09:00
from typing import Final
import requests
from pydantic import TypeAdapter
2023-05-01 20:00:32 +09:00
from pydantic.dataclasses import dataclass
from mdrsclient.api.base import BaseApi
from mdrsclient.exceptions import UnauthorizedException
from mdrsclient.models import Laboratory, Token, User
2023-05-01 20:00:32 +09:00
@dataclass(frozen=True)
class UserAuthResponse(Token):
is_reviewer: bool | None = None
laboratories: list[Laboratory] = field(default_factory=list)
2023-05-01 20:00:32 +09:00
class UserApi(BaseApi):
ENTRYPOINT: Final[str] = "v2/"
def auth(self, username: str, password: str) -> tuple[User, Token]:
2023-05-09 19:45:03 +09:00
# print(self.__class__.__name__ + "::" + sys._getframe().f_code.co_name)
2023-05-01 20:00:32 +09:00
url = self.ENTRYPOINT + "auth/"
data: dict[str, str | int] = {"username": username, "password": password}
2023-05-10 14:46:08 +09:00
response = self.connection.post(url, data=data)
2023-05-01 20:00:32 +09:00
if response.status_code == requests.codes.unauthorized:
raise UnauthorizedException("Invalid username or password.")
self._raise_response_error(response)
obj = TypeAdapter(UserAuthResponse).validate_python(response.json())
2023-05-01 20:00:32 +09:00
token = Token(access=obj.access, refresh=obj.refresh)
laboratory_ids = list(map(lambda x: x.id, obj.laboratories))
is_reviewer = obj.is_reviewer if obj.is_reviewer is not None else False
user = User(id=token.user_id, username=username, laboratory_ids=laboratory_ids, is_reviewer=is_reviewer)
2023-05-01 20:00:32 +09:00
return (user, token)
def refresh(self, token: Token) -> Token:
2023-05-09 19:45:03 +09:00
# print(self.__class__.__name__ + "::" + sys._getframe().f_code.co_name)
2023-05-01 20:00:32 +09:00
url = self.ENTRYPOINT + "refresh/"
data: dict[str, str | int] = {"refresh": token.refresh}
2023-05-10 14:46:08 +09:00
response = self.connection.post(url, data=data)
2023-05-01 20:00:32 +09:00
if response.status_code == requests.codes.unauthorized:
raise UnauthorizedException("Token is invalid or expired.")
self._raise_response_error(response)
token = TypeAdapter(Token).validate_python(response.json())
2023-05-01 20:00:32 +09:00
return token