mdrs-client-python/mdrsclient/api/users.py

68 lines
2.4 KiB
Python
Raw Permalink Normal View History

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
2023-12-12 20:05:46 +09:00
from mdrsclient.models import Token, User
2023-05-01 20:00:32 +09:00
@dataclass(frozen=True)
class UsersCurrentResponseLaboratory:
id: int
name: str
role: int
@dataclass(frozen=True)
2023-12-12 20:05:46 +09:00
class UsersApiCurrentResponse:
id: int
username: str
full_name: str
email: str
laboratories: list[UsersCurrentResponseLaboratory]
is_staff: bool
is_active: bool
is_superuser: bool
is_reviewer: bool
last_login: str # ISO8601
date_joined: str # ISO8601
class UsersApi(BaseApi):
2023-12-12 20:05:46 +09:00
ENTRYPOINT: Final[str] = "v3/users/"
2023-05-01 20:00:32 +09:00
def current(self) -> User:
2023-05-09 19:45:03 +09:00
# print(self.__class__.__name__ + "::" + sys._getframe().f_code.co_name)
2023-12-12 20:05:46 +09:00
url = self.ENTRYPOINT + "current/"
response = self.connection.get(url)
self._raise_response_error(response)
2023-12-12 20:05:46 +09:00
obj = TypeAdapter(UsersApiCurrentResponse).validate_python(response.json())
laboratory_ids = list(map(lambda x: x.id, obj.laboratories))
user = User(id=obj.id, username=obj.username, laboratory_ids=laboratory_ids, is_reviewer=obj.is_reviewer)
return user
def token(self, username: str, password: str) -> Token:
# print(self.__class__.__name__ + "::" + sys._getframe().f_code.co_name)
2023-12-12 20:05:46 +09:00
url = self.ENTRYPOINT + "token/"
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)
token = TypeAdapter(Token).validate_python(response.json())
return token
2023-05-01 20:00:32 +09:00
def tokenRefresh(self, token: Token) -> Token:
2023-05-09 19:45:03 +09:00
# print(self.__class__.__name__ + "::" + sys._getframe().f_code.co_name)
2023-12-12 20:05:46 +09:00
url = self.ENTRYPOINT + "token/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