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

44 lines
1.7 KiB
Python
Raw Normal View History

2023-05-01 20:00:32 +09:00
from typing import Final
import requests
from pydantic import parse_obj_as
from pydantic.dataclasses import dataclass
from mdrsclient.api.base import BaseApi
from mdrsclient.exceptions import UnauthorizedException
from mdrsclient.models import Token, User
@dataclass(frozen=True)
class UserAuthResponse(Token):
laboratory: str
lab_id: int
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 = {"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 = parse_obj_as(UserAuthResponse, response.json())
token = Token(access=obj.access, refresh=obj.refresh)
user = User(id=token.user_id, username=username, laboratory_id=obj.lab_id, laboratory=obj.laboratory)
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 = {"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 = parse_obj_as(Token, response.json())
return token