38 lines
1.4 KiB
Python

import getpass
from argparse import Namespace
from typing import Any
from mdrsclient.api import UserApi
from mdrsclient.commands.base import BaseCommand
from mdrsclient.config import ConfigFile
from mdrsclient.connection import MDRSConnection
from mdrsclient.exceptions import MissingConfigurationException
class LoginCommand(BaseCommand):
@classmethod
def register(cls, parsers: Any) -> None:
login_parser = parsers.add_parser("login", help="login to remote host")
login_parser.add_argument("remote", help="label of remote host")
login_parser.set_defaults(func=cls.func)
@classmethod
def func(cls, args: Namespace) -> None:
remote = str(args.remote)
username = input("Username: ").strip()
password = getpass.getpass("Password: ").strip()
cls.login(remote, username, password)
@classmethod
def login(cls, remote: str, username: str, password: str) -> None:
remote = cls._parse_remote_host(remote)
config = ConfigFile(remote)
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
connection.token = token