62 lines
2.6 KiB
Python
62 lines
2.6 KiB
Python
|
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.exceptions import MissingConfigurationException
|
||
|
from mdrsclient.session import MDRSSession
|
||
|
|
||
|
|
||
|
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.")
|
||
|
session = MDRSSession(config.remote, config.url)
|
||
|
username = input("Username: ").strip()
|
||
|
password = getpass.getpass("Password: ").strip()
|
||
|
user_api = UserApi(session)
|
||
|
(user, token) = user_api.auth(username, password)
|
||
|
session.user = user
|
||
|
session.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.")
|
||
|
session = MDRSSession(config.remote, config.url)
|
||
|
session.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.")
|
||
|
session = MDRSSession(config.remote, config.url)
|
||
|
if session.token is not None and session.token.is_expired:
|
||
|
session.logout()
|
||
|
username = session.user.username if session.user is not None else "(Anonymous)"
|
||
|
print(username)
|