import getpass from argparse import Namespace, _SubParsersAction from mdrsclient.api import UserApi from mdrsclient.commands.base import BaseCommand from mdrsclient.commands.utils import parse_remote_host from mdrsclient.config import ConfigFile from mdrsclient.connection import MDRSConnection from mdrsclient.exceptions import MissingConfigurationException class UserCommand(BaseCommand): @staticmethod def register(top_level_subparsers: _SubParsersAction) -> None: # login login_parser = top_level_subparsers.add_parser("login", help="login to remote host") login_parser.add_argument("remote", help="Label of remote host") login_parser.set_defaults(func=UserCommand.login) # logout logout_parser = top_level_subparsers.add_parser("logout", help="logout from remote host") logout_parser.add_argument("remote", help="Label of remote host") logout_parser.set_defaults(func=UserCommand.logout) # whoami whoami_parser = top_level_subparsers.add_parser("whoami", help="show current user name") whoami_parser.add_argument("remote", help="Label of remote host") whoami_parser.set_defaults(func=UserCommand.whoami) @staticmethod def login(args: Namespace) -> None: remote = parse_remote_host(args.remote) config = ConfigFile(remote) if config.url is None: raise MissingConfigurationException(f"Remote host `{remote}` is not found.") connection = MDRSConnection(config.remote, config.url) username = input("Username: ").strip() password = getpass.getpass("Password: ").strip() user_api = UserApi(connection) (user, token) = user_api.auth(username, password) connection.user = user connection.token = token @staticmethod def logout(args: Namespace) -> None: remote = parse_remote_host(args.remote) config = ConfigFile(remote) if config.url is None: raise MissingConfigurationException(f"Remote host `{remote}` is not found.") connection = MDRSConnection(config.remote, config.url) connection.logout() @staticmethod def whoami(args: Namespace) -> None: remote = parse_remote_host(args.remote) config = ConfigFile(remote) if config.url is None: raise MissingConfigurationException(f"Remote host `{remote}` is not found.") connection = MDRSConnection(config.remote, config.url) if connection.token is not None and connection.token.is_expired: connection.logout() username = connection.user.username if connection.user is not None else "(Anonymous)" print(username)