From f10b42a1f29e4fe41a9554fc2f6036d6ea21a1bc Mon Sep 17 00:00:00 2001 From: Yoshihiro OKUMURA Date: Thu, 7 Dec 2023 14:46:57 +0900 Subject: [PATCH] updated auth token handling using new users api. --- .cspell.json | 17 ++++++---- mdrsclient/VERSION | 2 +- mdrsclient/api/__init__.py | 4 +-- mdrsclient/api/{user.py => users.py} | 50 ++++++++++++++++++++++------ mdrsclient/api/utils.py | 6 ++-- mdrsclient/commands/login.py | 12 ++++--- mdrsclient/commands/ls.py | 7 ++-- mdrsclient/models/folder.py | 2 +- pyproject.toml | 10 +++--- 9 files changed, 73 insertions(+), 37 deletions(-) rename mdrsclient/api/{user.py => users.py} (54%) diff --git a/.cspell.json b/.cspell.json index e4ded8a..b742e8d 100644 --- a/.cspell.json +++ b/.cspell.json @@ -1,10 +1,15 @@ { "version": "0.2", "language": "en,en-gb", - "ignoreWords": ["getframe", "pydantic", "UNLCK"], - "words": ["chacl", "mdrs", "mdrsclient", "neurodata", "Neuroinformatics", "RIKEN"], - "ignorePaths": [ - ".env", - "__pycache__" - ] + "ignoreWords": ["getframe", "pycache", "pydantic", "UNLCK"], + "words": [ + "chacl", + "kikan", + "mdrs", + "mdrsclient", + "neurodata", + "Neuroinformatics", + "RIKEN" + ], + "ignorePaths": [".env", "__pycache__"] } diff --git a/mdrsclient/VERSION b/mdrsclient/VERSION index 26aaba0..f0bb29e 100644 --- a/mdrsclient/VERSION +++ b/mdrsclient/VERSION @@ -1 +1 @@ -1.2.0 +1.3.0 diff --git a/mdrsclient/api/__init__.py b/mdrsclient/api/__init__.py index 27e062c..8041591 100644 --- a/mdrsclient/api/__init__.py +++ b/mdrsclient/api/__init__.py @@ -1,11 +1,11 @@ from mdrsclient.api.file import FileApi from mdrsclient.api.folder import FolderApi from mdrsclient.api.laboratory import LaboratoryApi -from mdrsclient.api.user import UserApi +from mdrsclient.api.users import UsersApi __all__ = [ "FileApi", "FolderApi", "LaboratoryApi", - "UserApi", + "UsersApi", ] diff --git a/mdrsclient/api/user.py b/mdrsclient/api/users.py similarity index 54% rename from mdrsclient/api/user.py rename to mdrsclient/api/users.py index 01e951a..5fa6b76 100644 --- a/mdrsclient/api/user.py +++ b/mdrsclient/api/users.py @@ -16,27 +16,55 @@ class UserAuthResponse(Token): laboratories: list[Laboratory] = field(default_factory=list) -class UserApi(BaseApi): +@dataclass(frozen=True) +class UsersCurrentResponseLaboratory: + id: int + name: str + role: int + + +@dataclass(frozen=True) +class UsersCurrentResponse: + 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): ENTRYPOINT: Final[str] = "v2/" - def auth(self, username: str, password: str) -> tuple[User, Token]: + def current(self) -> User: # print(self.__class__.__name__ + "::" + sys._getframe().f_code.co_name) - url = self.ENTRYPOINT + "auth/" + url = self.ENTRYPOINT + "users/current/" + response = self.connection.get(url) + self._raise_response_error(response) + obj = TypeAdapter(UsersCurrentResponse).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) + url = self.ENTRYPOINT + "users/token/" data: dict[str, str | int] = {"username": username, "password": password} response = self.connection.post(url, data=data) 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()) - 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) - return (user, token) + token = TypeAdapter(Token).validate_python(response.json()) + return token - def refresh(self, token: Token) -> Token: + def tokenRefresh(self, token: Token) -> Token: # print(self.__class__.__name__ + "::" + sys._getframe().f_code.co_name) - url = self.ENTRYPOINT + "refresh/" + url = self.ENTRYPOINT + "users/token/refresh/" data: dict[str, str | int] = {"refresh": token.refresh} response = self.connection.post(url, data=data) if response.status_code == requests.codes.unauthorized: diff --git a/mdrsclient/api/utils.py b/mdrsclient/api/utils.py index 6a6fef7..6849304 100644 --- a/mdrsclient/api/utils.py +++ b/mdrsclient/api/utils.py @@ -1,4 +1,4 @@ -from mdrsclient.api.user import UserApi +from mdrsclient.api.users import UsersApi from mdrsclient.connection import MDRSConnection from mdrsclient.exceptions import UnauthorizedException @@ -8,9 +8,9 @@ def token_check(connection: MDRSConnection) -> None: connection.lock.acquire() if connection.token is not None: if connection.token.is_refresh_required: - user_api = UserApi(connection) + user_api = UsersApi(connection) try: - connection.token = user_api.refresh(connection.token) + connection.token = user_api.tokenRefresh(connection.token) except UnauthorizedException: connection.logout() elif connection.token.is_expired: diff --git a/mdrsclient/commands/login.py b/mdrsclient/commands/login.py index c399f02..135c825 100644 --- a/mdrsclient/commands/login.py +++ b/mdrsclient/commands/login.py @@ -2,7 +2,7 @@ import getpass from argparse import Namespace from typing import Any -from mdrsclient.api import UserApi +from mdrsclient.api import UsersApi from mdrsclient.commands.base import BaseCommand from mdrsclient.config import ConfigFile from mdrsclient.connection import MDRSConnection @@ -30,8 +30,10 @@ class LoginCommand(BaseCommand): if config.url is None: raise MissingConfigurationException(f"Remote host `{remote}` is not found.") connection = MDRSConnection(config.remote, config.url) - user_api = UserApi(connection) - (user, token) = user_api.auth(username, password) - print("Login Successful") - connection.user = user + user_api = UsersApi(connection) + token = user_api.token(username, password) connection.token = token + user = user_api.current() + connection.user = user + print(user) + print("Login Successful") diff --git a/mdrsclient/commands/ls.py b/mdrsclient/commands/ls.py index 87e3b07..feb6021 100644 --- a/mdrsclient/commands/ls.py +++ b/mdrsclient/commands/ls.py @@ -90,7 +90,7 @@ class LsCommand(BaseCommand): for key in label.keys(): length[key] = len(label[key]) if not context.is_quick else 0 for sub_folder in folder.sub_folders: - sub_laboratory = context.connection.laboratories.find_by_id(sub_folder.lab_id) + sub_laboratory = context.connection.laboratories.find_by_id(sub_folder.laboratory_id) sub_laboratory_name = sub_laboratory.name if sub_laboratory is not None else "(invalid)" length["acl"] = max(length["acl"], len(sub_folder.access_level_name)) length["laboratory"] = max(length["laboratory"], len(sub_laboratory_name)) @@ -118,7 +118,7 @@ class LsCommand(BaseCommand): print("-" * len(header.expandtabs())) for sub_folder in sorted(folder.sub_folders, key=lambda x: x.name): - sub_laboratory_name = cls._laboratory_name(context, sub_folder.lab_id) + sub_laboratory_name = cls._laboratory_name(context, sub_folder.laboratory_id) print( f"{'[d]':{length['type']}}\t{sub_folder.access_level_name:{length['acl']}}\t" f"{sub_laboratory_name:{length['laboratory']}}\t{sub_folder.lock_name:{length['size']}}\t" @@ -151,13 +151,14 @@ class LsCommand(BaseCommand): "name": folder.name, "access_level": folder.access_level_name, "lock": folder.lock, - "laboratory": cls._laboratory_name(context, folder.lab_id), + "laboratory": cls._laboratory_name(context, folder.laboratory_id), "description": folder.description, "created_at": folder.created_at, "updated_at": folder.updated_at, } if isinstance(folder, Folder): folder_api = FolderApi(context.connection) + print(folder.name) data["metadata"] = folder_api.metadata(folder.id) if context.is_recursive: sub_folders: list[dict[str, Any]] = [] diff --git a/mdrsclient/models/folder.py b/mdrsclient/models/folder.py index 8fa5d88..23d3d00 100644 --- a/mdrsclient/models/folder.py +++ b/mdrsclient/models/folder.py @@ -49,7 +49,7 @@ class FolderSimple: name: str access_level: int lock: bool - lab_id: int + laboratory_id: int description: str created_at: str updated_at: str diff --git a/pyproject.toml b/pyproject.toml index 75b7416..afdefbe 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "mdrs-client-python" -version = "1.2.0" +version = "1.3.0" description = "The mdrs-client-python is python library and a command-line client for up- and downloading files to and from MDRS based repository." authors = ["Yoshihiro OKUMURA "] license = "MIT" @@ -24,17 +24,17 @@ packages = [ python = "^3.10" requests = "^2.31.0" python-dotenv = "^1.0.0" -pydantic = "^2.4.2" -pydantic-settings = "^2.0.3" +pydantic = "^2.5.2" +pydantic-settings = "^2.1.0" PyJWT = "^2.8.0" validators = "^0.22.0" [tool.poetry.group.dev.dependencies] -black = "^23.9.1" +black = "^23.11.0" flake8 = "^6.1.0" Flake8-pyproject = "^1.2.3" isort = "^5.12.0" -pyright = "^1.1.329" +pyright = "^1.1.339" [tool.poetry.scripts] mdrs = 'mdrsclient.__main__:main'