From 40c816b1681fd093b4e879e01895391b85cc8386 Mon Sep 17 00:00:00 2001 From: jobala Date: Mon, 16 Nov 2020 14:21:02 +0300 Subject: [PATCH 01/32] Add cloud commands --- .../cli/command_modules/profile/__init__.py | 32 ++++++++++++ .../profile/_exception_handler.py | 11 +++++ msgraph/cli/command_modules/profile/_help.py | 0 msgraph/cli/command_modules/profile/custom.py | 49 +++++++++++++++++++ msgraph/cli/core/installed_extensions.py | 48 +++++++++--------- 5 files changed, 116 insertions(+), 24 deletions(-) create mode 100644 msgraph/cli/command_modules/profile/__init__.py create mode 100644 msgraph/cli/command_modules/profile/_exception_handler.py create mode 100644 msgraph/cli/command_modules/profile/_help.py create mode 100644 msgraph/cli/command_modules/profile/custom.py diff --git a/msgraph/cli/command_modules/profile/__init__.py b/msgraph/cli/command_modules/profile/__init__.py new file mode 100644 index 00000000..a775d71f --- /dev/null +++ b/msgraph/cli/command_modules/profile/__init__.py @@ -0,0 +1,32 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +from msgraph.cli.core import AzCommandsLoader +from msgraph.cli.core.commands import CliCommandType +from msgraph.cli.command_modules.profile._exception_handler import profile_exception_handler +import msgraph.cli.command_modules.profile._help + + +class ProfileCommandsLoader(AzCommandsLoader): + """Provides profile commands to msgraph-cli + """ + def __init__(self, cli_ctx, **kwargs): + super().__init__(cli_ctx, **kwargs) + + def load_command_table(self, args): + # operations_tmpl is the file that contains the implementation of the command + command_type = CliCommandType( + operations_tmpl='msgraph.cli.command_modules.profile.custom#{}', + exception_handler=profile_exception_handler) + with self.command_group('cloud', command_type) as group: + group.command('list', 'list_clouds') + group.command('select', 'select_cloud') + group.command('add', 'add_cloud') + group.command('reset', 'reset_cloud') + + return self.command_table + + +COMMAND_LOADER_CLS = ProfileCommandsLoader \ No newline at end of file diff --git a/msgraph/cli/command_modules/profile/_exception_handler.py b/msgraph/cli/command_modules/profile/_exception_handler.py new file mode 100644 index 00000000..c341fa80 --- /dev/null +++ b/msgraph/cli/command_modules/profile/_exception_handler.py @@ -0,0 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +from knack.cli import CLIError + + +def profile_exception_handler(exception): + raise CLIError(exception) \ No newline at end of file diff --git a/msgraph/cli/command_modules/profile/_help.py b/msgraph/cli/command_modules/profile/_help.py new file mode 100644 index 00000000..e69de29b diff --git a/msgraph/cli/command_modules/profile/custom.py b/msgraph/cli/command_modules/profile/custom.py new file mode 100644 index 00000000..98dff652 --- /dev/null +++ b/msgraph/cli/command_modules/profile/custom.py @@ -0,0 +1,49 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +CLOUDS = { + 'PUBLIC': { + 'client_id': '', + 'endpoint': 'graph.microsoft.com', + 'authority': 'https://login.microsoftonline.com' + }, + 'US_GOV_L4': { + 'client_id': '', + 'endpoint': 'https://graph.microsoft.us', + 'authority': 'https://login.microsoftonline.us' + }, + 'US_GOV_L5': { + 'client_id': '', + 'endpoint': 'https://dod-graph.microsoft.us', + 'authority': 'https://login.microsoftonline.us' + }, + 'GERMANY': { + 'client_id': '', + 'endpoint': 'https://graph.microsoft.de', + 'authority': 'https://login.microsoftonline.de' + }, + 'CHINA': { + 'client_id': '', + 'endpoint': 'https://microsoftgraph.chinacloudapi.cn', + 'authority': ' https://login.chinacloudapi.cn' + } +} + + +def list_clouds(): + for cloud in list(CLOUDS.keys()): + print(cloud) + + +def select_cloud(): + print('Selecting a cloud') + + +def add_cloud(): + print('Adding a cloud') + + +def reset_cloud(): + print('Resetting a cloud') diff --git a/msgraph/cli/core/installed_extensions.py b/msgraph/cli/core/installed_extensions.py index f2a8af82..b1af9466 100644 --- a/msgraph/cli/core/installed_extensions.py +++ b/msgraph/cli/core/installed_extensions.py @@ -1,25 +1,25 @@ -installed_extensions = [ - 'azext_schemaextensions', - 'azext_cloudcommunications', - 'azext_calendar', - 'azext_usersfunctions', - 'azext_security', - 'azext_mail', - 'azext_planner', - 'azext_education', - 'azext_sites', - 'azext_changenotifications', - 'azext_notes', - 'azext_users', - 'azext_usersactions', - 'azext_people', - 'azext_teams', - 'azext_applications', - 'azext_files', - 'azext_identitydirectorymanagement', - 'azext_directoryobjects', - 'azext_crossdeviceexperiences', - 'azext_personalcontacts', - 'azext_identitysignins', - 'azext_reports', +installed_extensions = [ + 'azext_applications', + 'azext_calendar', + 'azext_changenotifications', + 'azext_cloudcommunications', + 'azext_crossdeviceexperiences', + 'azext_directoryobjects', + 'azext_education', + 'azext_files', + 'azext_identitydirectorymanagement', + 'azext_identitysignins', + 'azext_mail', + 'azext_notes', + 'azext_people', + 'azext_personalcontacts', + 'azext_planner', + 'azext_reports', + 'azext_schemaextensions', + 'azext_security', + 'azext_sites', + 'azext_teams', + 'azext_users', + 'azext_usersactions', + 'azext_usersfunctions', ] \ No newline at end of file From eb0a7a60113bb95908c60269a943277372e0f99f Mon Sep 17 00:00:00 2001 From: jobala Date: Mon, 16 Nov 2020 14:22:52 +0300 Subject: [PATCH 02/32] Move profile --- msgraph/{cli => }/command_modules/profile/__init__.py | 0 msgraph/{cli => }/command_modules/profile/_exception_handler.py | 0 msgraph/{cli => }/command_modules/profile/_help.py | 0 msgraph/{cli => }/command_modules/profile/custom.py | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename msgraph/{cli => }/command_modules/profile/__init__.py (100%) rename msgraph/{cli => }/command_modules/profile/_exception_handler.py (100%) rename msgraph/{cli => }/command_modules/profile/_help.py (100%) rename msgraph/{cli => }/command_modules/profile/custom.py (100%) diff --git a/msgraph/cli/command_modules/profile/__init__.py b/msgraph/command_modules/profile/__init__.py similarity index 100% rename from msgraph/cli/command_modules/profile/__init__.py rename to msgraph/command_modules/profile/__init__.py diff --git a/msgraph/cli/command_modules/profile/_exception_handler.py b/msgraph/command_modules/profile/_exception_handler.py similarity index 100% rename from msgraph/cli/command_modules/profile/_exception_handler.py rename to msgraph/command_modules/profile/_exception_handler.py diff --git a/msgraph/cli/command_modules/profile/_help.py b/msgraph/command_modules/profile/_help.py similarity index 100% rename from msgraph/cli/command_modules/profile/_help.py rename to msgraph/command_modules/profile/_help.py diff --git a/msgraph/cli/command_modules/profile/custom.py b/msgraph/command_modules/profile/custom.py similarity index 100% rename from msgraph/cli/command_modules/profile/custom.py rename to msgraph/command_modules/profile/custom.py From 309ccbcb0a353edefb390fa3ce61430971f9c668 Mon Sep 17 00:00:00 2001 From: jobala Date: Mon, 16 Nov 2020 16:06:19 +0300 Subject: [PATCH 03/32] Supports selecting a cloud --- msgraph/cli/core/authentication.py | 3 +- msgraph/command_modules/profile/__init__.py | 9 ++-- msgraph/command_modules/profile/_help.py | 11 +++++ msgraph/command_modules/profile/constants.py | 33 +++++++++++++ msgraph/command_modules/profile/custom.py | 51 +++++--------------- 5 files changed, 62 insertions(+), 45 deletions(-) create mode 100644 msgraph/command_modules/profile/constants.py diff --git a/msgraph/cli/core/authentication.py b/msgraph/cli/core/authentication.py index 72debca6..8e7239e9 100644 --- a/msgraph/cli/core/authentication.py +++ b/msgraph/cli/core/authentication.py @@ -2,10 +2,9 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- -import sys + from os import path, remove from azure.identity import InteractiveBrowserCredential, AuthenticationRecord -import logging from msgraph.cli.core.constants import AUTH_RECORD_LOCATION, CLIENT_ID from msgraph.cli.core.exceptions import CLIException diff --git a/msgraph/command_modules/profile/__init__.py b/msgraph/command_modules/profile/__init__.py index a775d71f..a341a9d8 100644 --- a/msgraph/command_modules/profile/__init__.py +++ b/msgraph/command_modules/profile/__init__.py @@ -5,8 +5,8 @@ from msgraph.cli.core import AzCommandsLoader from msgraph.cli.core.commands import CliCommandType -from msgraph.cli.command_modules.profile._exception_handler import profile_exception_handler -import msgraph.cli.command_modules.profile._help +from msgraph.command_modules.profile._exception_handler import profile_exception_handler +import msgraph.command_modules.profile._help class ProfileCommandsLoader(AzCommandsLoader): @@ -17,9 +17,8 @@ def __init__(self, cli_ctx, **kwargs): def load_command_table(self, args): # operations_tmpl is the file that contains the implementation of the command - command_type = CliCommandType( - operations_tmpl='msgraph.cli.command_modules.profile.custom#{}', - exception_handler=profile_exception_handler) + command_type = CliCommandType(operations_tmpl='msgraph.command_modules.profile.custom#{}', + exception_handler=profile_exception_handler) with self.command_group('cloud', command_type) as group: group.command('list', 'list_clouds') group.command('select', 'select_cloud') diff --git a/msgraph/command_modules/profile/_help.py b/msgraph/command_modules/profile/_help.py index e69de29b..e40822c7 100644 --- a/msgraph/command_modules/profile/_help.py +++ b/msgraph/command_modules/profile/_help.py @@ -0,0 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +from knack.help_files import helps + +helps['select'] = """ +type: command +short-summary: Select a cloud from supported clouds. +""" \ No newline at end of file diff --git a/msgraph/command_modules/profile/constants.py b/msgraph/command_modules/profile/constants.py new file mode 100644 index 00000000..25fe6f3f --- /dev/null +++ b/msgraph/command_modules/profile/constants.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +CLOUDS = { + 'PUBLIC': { + 'client_id': 'f7218512-c727-4138-9fb9-a0fe2500650c', + 'endpoint': 'graph.microsoft.com', + 'authority': 'https://login.microsoftonline.com' + }, + 'US_GOV_L4': { + 'client_id': '', + 'endpoint': 'https://graph.microsoft.us', + 'authority': 'https://login.microsoftonline.us' + }, + 'US_GOV_L5': { + 'client_id': '', + 'endpoint': 'https://dod-graph.microsoft.us', + 'authority': 'https://login.microsoftonline.us' + }, + 'GERMANY': { + 'client_id': '', + 'endpoint': 'https://graph.microsoft.de', + 'authority': 'https://login.microsoftonline.de' + }, + 'CHINA': { + 'client_id': '', + 'endpoint': 'https://microsoftgraph.chinacloudapi.cn', + 'authority': ' https://login.chinacloudapi.cn' + } +} diff --git a/msgraph/command_modules/profile/custom.py b/msgraph/command_modules/profile/custom.py index 98dff652..db81c1a3 100644 --- a/msgraph/command_modules/profile/custom.py +++ b/msgraph/command_modules/profile/custom.py @@ -1,44 +1,19 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -CLOUDS = { - 'PUBLIC': { - 'client_id': '', - 'endpoint': 'graph.microsoft.com', - 'authority': 'https://login.microsoftonline.com' - }, - 'US_GOV_L4': { - 'client_id': '', - 'endpoint': 'https://graph.microsoft.us', - 'authority': 'https://login.microsoftonline.us' - }, - 'US_GOV_L5': { - 'client_id': '', - 'endpoint': 'https://dod-graph.microsoft.us', - 'authority': 'https://login.microsoftonline.us' - }, - 'GERMANY': { - 'client_id': '', - 'endpoint': 'https://graph.microsoft.de', - 'authority': 'https://login.microsoftonline.de' - }, - 'CHINA': { - 'client_id': '', - 'endpoint': 'https://microsoftgraph.chinacloudapi.cn', - 'authority': ' https://login.chinacloudapi.cn' - } -} - - -def list_clouds(): - for cloud in list(CLOUDS.keys()): - print(cloud) +# coding=utf-8 +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +from knack.prompting import prompt_choice_list + +from .constants import CLOUDS def select_cloud(): - print('Selecting a cloud') + supported_clouds = list(CLOUDS.keys()) + selected = prompt_choice_list('Select a cloud', supported_clouds) + print(f'Selected {supported_clouds[selected]}') + # Save selected cloud in profile.json def add_cloud(): From 3823f8a9706a804a34d8cb575afaa2d86697f1bd Mon Sep 17 00:00:00 2001 From: jobala Date: Tue, 17 Nov 2020 12:49:42 +0300 Subject: [PATCH 04/32] Remove list clouds --- msgraph/command_modules/profile/__init__.py | 1 - 1 file changed, 1 deletion(-) diff --git a/msgraph/command_modules/profile/__init__.py b/msgraph/command_modules/profile/__init__.py index a341a9d8..1b8da6a0 100644 --- a/msgraph/command_modules/profile/__init__.py +++ b/msgraph/command_modules/profile/__init__.py @@ -20,7 +20,6 @@ def load_command_table(self, args): command_type = CliCommandType(operations_tmpl='msgraph.command_modules.profile.custom#{}', exception_handler=profile_exception_handler) with self.command_group('cloud', command_type) as group: - group.command('list', 'list_clouds') group.command('select', 'select_cloud') group.command('add', 'add_cloud') group.command('reset', 'reset_cloud') From ec9388b2d624e64de780867f386c2fcd6a517c02 Mon Sep 17 00:00:00 2001 From: jobala Date: Tue, 17 Nov 2020 14:50:31 +0300 Subject: [PATCH 05/32] Supports user defined clouds --- msgraph/cli/core/authentication.py | 1 + msgraph/command_modules/profile/_help.py | 6 ++- msgraph/command_modules/profile/constants.py | 9 +--- msgraph/command_modules/profile/custom.py | 53 +++++++++++++++++++- 4 files changed, 58 insertions(+), 11 deletions(-) diff --git a/msgraph/cli/core/authentication.py b/msgraph/cli/core/authentication.py index 8e7239e9..f34026c9 100644 --- a/msgraph/cli/core/authentication.py +++ b/msgraph/cli/core/authentication.py @@ -42,6 +42,7 @@ def get_credential(self, auth_record=None) -> InteractiveBrowserCredential: ValueError If PyGObject is not installed in the host Linux OS. ''' + # TODO: get authority from profile.json return InteractiveBrowserCredential( client_id=CLIENT_ID, enable_persistent_cache=True, diff --git a/msgraph/command_modules/profile/_help.py b/msgraph/command_modules/profile/_help.py index e40822c7..6fa312e2 100644 --- a/msgraph/command_modules/profile/_help.py +++ b/msgraph/command_modules/profile/_help.py @@ -5,7 +5,9 @@ # -------------------------------------------------------------------------------------------- from knack.help_files import helps -helps['select'] = """ +helps['cloud select'] = """ type: command short-summary: Select a cloud from supported clouds. -""" \ No newline at end of file +""" + +#TODO: Add help for cloud add \ No newline at end of file diff --git a/msgraph/command_modules/profile/constants.py b/msgraph/command_modules/profile/constants.py index 25fe6f3f..13beb6af 100644 --- a/msgraph/command_modules/profile/constants.py +++ b/msgraph/command_modules/profile/constants.py @@ -6,28 +6,23 @@ CLOUDS = { 'PUBLIC': { - 'client_id': 'f7218512-c727-4138-9fb9-a0fe2500650c', - 'endpoint': 'graph.microsoft.com', + 'endpoint': 'https://graph.microsoft.com', 'authority': 'https://login.microsoftonline.com' }, 'US_GOV_L4': { - 'client_id': '', 'endpoint': 'https://graph.microsoft.us', 'authority': 'https://login.microsoftonline.us' }, 'US_GOV_L5': { - 'client_id': '', 'endpoint': 'https://dod-graph.microsoft.us', 'authority': 'https://login.microsoftonline.us' }, 'GERMANY': { - 'client_id': '', 'endpoint': 'https://graph.microsoft.de', 'authority': 'https://login.microsoftonline.de' }, 'CHINA': { - 'client_id': '', 'endpoint': 'https://microsoftgraph.chinacloudapi.cn', - 'authority': ' https://login.chinacloudapi.cn' + 'authority': 'https://login.chinacloudapi.cn' } } diff --git a/msgraph/command_modules/profile/custom.py b/msgraph/command_modules/profile/custom.py index db81c1a3..b70ac92b 100644 --- a/msgraph/command_modules/profile/custom.py +++ b/msgraph/command_modules/profile/custom.py @@ -4,21 +4,70 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- +from os import path +from pathlib import Path +import json from knack.prompting import prompt_choice_list +from msgraph.cli.core.exceptions import CLIException from .constants import CLOUDS +#TODO: Move this variable to constants.py +PROFILE_LOCATION = path.join(Path.home(), '.mg', 'profile.json') + def select_cloud(): + profile = read_profile() + + user_defined_clouds = profile.get('user_defined_clouds', {}) + + for cloud in user_defined_clouds: + CLOUDS.update(cloud) + supported_clouds = list(CLOUDS.keys()) selected = prompt_choice_list('Select a cloud', supported_clouds) + + profile['cloud'] = CLOUDS.get(supported_clouds[selected]) + write_profile(json.dumps(profile)) + print(f'Selected {supported_clouds[selected]}') # Save selected cloud in profile.json -def add_cloud(): - print('Adding a cloud') +def add_cloud(name: str, endpoint: str, authority: str): + cloud = {name: {'endpoint': endpoint, 'authority': authority}} + + profile = read_profile() + + try: + user_defined_clouds = profile['user_defined_clouds'] + user_defined_clouds.append(cloud) + except KeyError: + profile['user_defined_clouds'] = [cloud] + + write_profile(json.dumps(profile)) + print(f'Cloud "{name}" added successfully') def reset_cloud(): print('Resetting a cloud') + + +#TODO: Abstract reading and writing to profile +def read_profile() -> dict: + result = None + + try: + with open(PROFILE_LOCATION, 'r') as file: + result = file.read() + return json.loads(result) + except IOError as ex: + return {} + + +def write_profile(profile: str): + try: + with open(PROFILE_LOCATION, 'w') as file: + file.write(profile) + except IOError as ex: + raise CLIException('Selected cloud was not set, CLI will use the PublicCLoud') from ex From 816a37d383a010d7298924359a9de7c92dc4e615 Mon Sep 17 00:00:00 2001 From: jobala Date: Tue, 17 Nov 2020 15:43:47 +0300 Subject: [PATCH 06/32] Add help information --- msgraph/cli/core/authentication.py | 1 + msgraph/command_modules/profile/_help.py | 19 ++++++++++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/msgraph/cli/core/authentication.py b/msgraph/cli/core/authentication.py index f34026c9..94448f53 100644 --- a/msgraph/cli/core/authentication.py +++ b/msgraph/cli/core/authentication.py @@ -11,6 +11,7 @@ class Authentication: + # TODO: Allow users to pass client id def login(self, scopes: [str]) -> bool: try: credential = self.get_credential() diff --git a/msgraph/command_modules/profile/_help.py b/msgraph/command_modules/profile/_help.py index 6fa312e2..13959d00 100644 --- a/msgraph/command_modules/profile/_help.py +++ b/msgraph/command_modules/profile/_help.py @@ -10,4 +10,21 @@ short-summary: Select a cloud from supported clouds. """ -#TODO: Add help for cloud add \ No newline at end of file +helps['cloud add'] = """ +type: command +short-summary: Add a custom cloud +parameters: + - name: --name + type: string + short-summary: Cloud's name + long-summary: The cloud's name is shown in the list of clouds when a user runs mg cloud select. + - name: --endpoint + type: string + short-summary: Cloud's endpoint + - name: --authority + short-summary: Cloud's authentication endpoint +examples: + - name: Add a new cloud + text: > + mg cloud add --name CUSTOM_CLOUD --endpoint https://graph.microsoft.com --authority https://graph.microsoftonline.com +""" \ No newline at end of file From be657caea8b010c8401755d25a152a062aaae925 Mon Sep 17 00:00:00 2001 From: jobala Date: Tue, 17 Nov 2020 15:58:08 +0300 Subject: [PATCH 07/32] Move constants into msgraph.cli.core --- msgraph/cli/__init__.py | 2 + msgraph/cli/core/constants.py | 24 +++++++++++ msgraph/cli/core/profile.py | 22 ++++++++++ msgraph/command_modules/profile/__init__.py | 1 - msgraph/command_modules/profile/constants.py | 28 ------------- msgraph/command_modules/profile/custom.py | 44 ++++---------------- 6 files changed, 55 insertions(+), 66 deletions(-) create mode 100644 msgraph/cli/core/profile.py delete mode 100644 msgraph/command_modules/profile/constants.py diff --git a/msgraph/cli/__init__.py b/msgraph/cli/__init__.py index b74cfa3b..c79f5449 100644 --- a/msgraph/cli/__init__.py +++ b/msgraph/cli/__init__.py @@ -2,3 +2,5 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ + +from .core.profile import read_profile, write_profile \ No newline at end of file diff --git a/msgraph/cli/core/constants.py b/msgraph/cli/core/constants.py index fb1d6491..11e87f99 100644 --- a/msgraph/cli/core/constants.py +++ b/msgraph/cli/core/constants.py @@ -7,6 +7,7 @@ from os import path AUTH_RECORD_LOCATION = path.join(Path.home(), '.mg', 'record.txt') +PROFILE_LOCATION = path.join(Path.home(), '.mg', 'profile.json') CLIENT_ID = 'f7218512-c727-4138-9fb9-a0fe2500650c' CLI_COMMON_KWARGS = [ @@ -24,3 +25,26 @@ 'self', 'raw', 'polling', 'custom_headers', 'operation_config', 'content_version', 'kwargs', 'client', 'no_wait' ] + +DEFAULT_CLOUDS = { + 'PUBLIC': { + 'endpoint': 'https://graph.microsoft.com', + 'authority': 'https://login.microsoftonline.com' + }, + 'US_GOV_L4': { + 'endpoint': 'https://graph.microsoft.us', + 'authority': 'https://login.microsoftonline.us' + }, + 'US_GOV_L5': { + 'endpoint': 'https://dod-graph.microsoft.us', + 'authority': 'https://login.microsoftonline.us' + }, + 'GERMANY': { + 'endpoint': 'https://graph.microsoft.de', + 'authority': 'https://login.microsoftonline.de' + }, + 'CHINA': { + 'endpoint': 'https://microsoftgraph.chinacloudapi.cn', + 'authority': 'https://login.chinacloudapi.cn' + } +} \ No newline at end of file diff --git a/msgraph/cli/core/profile.py b/msgraph/cli/core/profile.py new file mode 100644 index 00000000..efc5725d --- /dev/null +++ b/msgraph/cli/core/profile.py @@ -0,0 +1,22 @@ +import json +from msgraph.cli.core.constants import PROFILE_LOCATION +from msgraph.cli.core.exceptions import CLIException + + +def read_profile() -> dict: + result = None + + try: + with open(PROFILE_LOCATION, 'r') as file: + result = file.read() + return json.loads(result) + except IOError as ex: + return {} + + +def write_profile(profile: str): + try: + with open(PROFILE_LOCATION, 'w') as file: + file.write(profile) + except IOError as ex: + raise CLIException('Selected cloud was not set, CLI will use the PublicCLoud') from ex \ No newline at end of file diff --git a/msgraph/command_modules/profile/__init__.py b/msgraph/command_modules/profile/__init__.py index 1b8da6a0..2b84bc51 100644 --- a/msgraph/command_modules/profile/__init__.py +++ b/msgraph/command_modules/profile/__init__.py @@ -22,7 +22,6 @@ def load_command_table(self, args): with self.command_group('cloud', command_type) as group: group.command('select', 'select_cloud') group.command('add', 'add_cloud') - group.command('reset', 'reset_cloud') return self.command_table diff --git a/msgraph/command_modules/profile/constants.py b/msgraph/command_modules/profile/constants.py deleted file mode 100644 index 13beb6af..00000000 --- a/msgraph/command_modules/profile/constants.py +++ /dev/null @@ -1,28 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -CLOUDS = { - 'PUBLIC': { - 'endpoint': 'https://graph.microsoft.com', - 'authority': 'https://login.microsoftonline.com' - }, - 'US_GOV_L4': { - 'endpoint': 'https://graph.microsoft.us', - 'authority': 'https://login.microsoftonline.us' - }, - 'US_GOV_L5': { - 'endpoint': 'https://dod-graph.microsoft.us', - 'authority': 'https://login.microsoftonline.us' - }, - 'GERMANY': { - 'endpoint': 'https://graph.microsoft.de', - 'authority': 'https://login.microsoftonline.de' - }, - 'CHINA': { - 'endpoint': 'https://microsoftgraph.chinacloudapi.cn', - 'authority': 'https://login.chinacloudapi.cn' - } -} diff --git a/msgraph/command_modules/profile/custom.py b/msgraph/command_modules/profile/custom.py index b70ac92b..1d073e97 100644 --- a/msgraph/command_modules/profile/custom.py +++ b/msgraph/command_modules/profile/custom.py @@ -3,17 +3,10 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- - -from os import path -from pathlib import Path import json from knack.prompting import prompt_choice_list -from msgraph.cli.core.exceptions import CLIException - -from .constants import CLOUDS - -#TODO: Move this variable to constants.py -PROFILE_LOCATION = path.join(Path.home(), '.mg', 'profile.json') +from msgraph.cli.core.constants import DEFAULT_CLOUDS +from msgraph.cli import read_profile, write_profile def select_cloud(): @@ -22,19 +15,20 @@ def select_cloud(): user_defined_clouds = profile.get('user_defined_clouds', {}) for cloud in user_defined_clouds: - CLOUDS.update(cloud) + DEFAULT_CLOUDS.update(cloud) - supported_clouds = list(CLOUDS.keys()) + supported_clouds = list(DEFAULT_CLOUDS.keys()) selected = prompt_choice_list('Select a cloud', supported_clouds) - profile['cloud'] = CLOUDS.get(supported_clouds[selected]) + profile['cloud'] = DEFAULT_CLOUDS.get(supported_clouds[selected]) write_profile(json.dumps(profile)) print(f'Selected {supported_clouds[selected]}') - # Save selected cloud in profile.json def add_cloud(name: str, endpoint: str, authority: str): + #TODO: validate that endpoint and authority are valid urls + cloud = {name: {'endpoint': endpoint, 'authority': authority}} profile = read_profile() @@ -47,27 +41,3 @@ def add_cloud(name: str, endpoint: str, authority: str): write_profile(json.dumps(profile)) print(f'Cloud "{name}" added successfully') - - -def reset_cloud(): - print('Resetting a cloud') - - -#TODO: Abstract reading and writing to profile -def read_profile() -> dict: - result = None - - try: - with open(PROFILE_LOCATION, 'r') as file: - result = file.read() - return json.loads(result) - except IOError as ex: - return {} - - -def write_profile(profile: str): - try: - with open(PROFILE_LOCATION, 'w') as file: - file.write(profile) - except IOError as ex: - raise CLIException('Selected cloud was not set, CLI will use the PublicCLoud') from ex From e82f31d6e8e8bbe71c39a9e87b3e89f6b61167b2 Mon Sep 17 00:00:00 2001 From: jobala Date: Wed, 18 Nov 2020 15:08:54 +0300 Subject: [PATCH 08/32] Validate endpoint --- msgraph/command_modules/profile/custom.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/msgraph/command_modules/profile/custom.py b/msgraph/command_modules/profile/custom.py index 1d073e97..7f7c40f3 100644 --- a/msgraph/command_modules/profile/custom.py +++ b/msgraph/command_modules/profile/custom.py @@ -11,23 +11,20 @@ def select_cloud(): profile = read_profile() - user_defined_clouds = profile.get('user_defined_clouds', {}) for cloud in user_defined_clouds: DEFAULT_CLOUDS.update(cloud) - supported_clouds = list(DEFAULT_CLOUDS.keys()) - selected = prompt_choice_list('Select a cloud', supported_clouds) + selected = prompt_choice_list('Select a cloud', supported_clouds) profile['cloud'] = DEFAULT_CLOUDS.get(supported_clouds[selected]) write_profile(json.dumps(profile)) - print(f'Selected {supported_clouds[selected]}') def add_cloud(name: str, endpoint: str, authority: str): - #TODO: validate that endpoint and authority are valid urls + _validate(endpoint) cloud = {name: {'endpoint': endpoint, 'authority': authority}} @@ -41,3 +38,12 @@ def add_cloud(name: str, endpoint: str, authority: str): write_profile(json.dumps(profile)) print(f'Cloud "{name}" added successfully') + + +def _validate(url: str): + from urllib import request + + try: + request.urlopen(url) + except IOError as error: + raise Exception('Invalid endpoint') \ No newline at end of file From 6c25da7a8d9ca284e9eea0be460e7ebc54f90e4a Mon Sep 17 00:00:00 2001 From: jobala Date: Wed, 18 Nov 2020 15:19:58 +0300 Subject: [PATCH 09/32] Accept user provided client_id and read authority from user profile --- msgraph/cli/core/authentication.py | 17 ++++++++++++----- .../command_modules/authentication/custom.py | 4 ++-- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/msgraph/cli/core/authentication.py b/msgraph/cli/core/authentication.py index 94448f53..9cf6d2fe 100644 --- a/msgraph/cli/core/authentication.py +++ b/msgraph/cli/core/authentication.py @@ -8,13 +8,14 @@ from msgraph.cli.core.constants import AUTH_RECORD_LOCATION, CLIENT_ID from msgraph.cli.core.exceptions import CLIException +from msgraph.cli import read_profile class Authentication: # TODO: Allow users to pass client id - def login(self, scopes: [str]) -> bool: + def login(self, scopes: [str], client_id=None) -> bool: try: - credential = self.get_credential() + credential = self.get_credential(client_id) auth_record = credential.authenticate(scopes=scopes) if auth_record is None: @@ -36,16 +37,22 @@ def logout(self): # By deleting the authentication record, we logout the user self._delete_auth_record() - def get_credential(self, auth_record=None) -> InteractiveBrowserCredential: + def get_credential(self, auth_record=None, user_client_id=None) -> InteractiveBrowserCredential: ''' Raises ------ ValueError If PyGObject is not installed in the host Linux OS. ''' - # TODO: get authority from profile.json + profile = read_profile() + user_cloud = profile.get('cloud', None) + + authority = user_cloud['authority'] if user_cloud else 'https://graph.microsoftonline.com' + client_id = user_client_id or CLIENT_ID + return InteractiveBrowserCredential( - client_id=CLIENT_ID, + authority=authority, + client_id=client_id, enable_persistent_cache=True, allow_unencrypted_cache=False, authentication_record=auth_record, diff --git a/msgraph/command_modules/authentication/custom.py b/msgraph/command_modules/authentication/custom.py index 99816533..57c1e793 100644 --- a/msgraph/command_modules/authentication/custom.py +++ b/msgraph/command_modules/authentication/custom.py @@ -9,11 +9,11 @@ authentication = Authentication() -def login(scopes): +def login(scopes: str, client_id=None): # Stripping whitespaces so that users don't have to worry about how # they enter scopes. ie "user.read, mail.read" or "user.read,mail.read" scopes = [scope.strip() for scope in scopes.split(',')] - logged_in = authentication.login(scopes) + logged_in = authentication.login(scopes, client_id) if not logged_in: raise CLIError('Login failed') From d9c08a56e65a61f364f1d9c7402769c06586917d Mon Sep 17 00:00:00 2001 From: jobala Date: Thu, 19 Nov 2020 15:07:55 +0300 Subject: [PATCH 10/32] Use cloud endpoint as base url --- msgraph/cli/core/authentication.py | 7 +++---- msgraph/cli/core/commands/client_factory.py | 11 ++++++++++- msgraph/cli/core/constants.py | 2 +- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/msgraph/cli/core/authentication.py b/msgraph/cli/core/authentication.py index 9cf6d2fe..af8e748b 100644 --- a/msgraph/cli/core/authentication.py +++ b/msgraph/cli/core/authentication.py @@ -8,14 +8,13 @@ from msgraph.cli.core.constants import AUTH_RECORD_LOCATION, CLIENT_ID from msgraph.cli.core.exceptions import CLIException -from msgraph.cli import read_profile +from msgraph.cli.core.profile import read_profile class Authentication: - # TODO: Allow users to pass client id def login(self, scopes: [str], client_id=None) -> bool: try: - credential = self.get_credential(client_id) + credential = self.get_credential(user_client_id=client_id) auth_record = credential.authenticate(scopes=scopes) if auth_record is None: @@ -47,7 +46,7 @@ def get_credential(self, auth_record=None, user_client_id=None) -> InteractiveBr profile = read_profile() user_cloud = profile.get('cloud', None) - authority = user_cloud['authority'] if user_cloud else 'https://graph.microsoftonline.com' + authority = user_cloud['authority'] if user_cloud else 'https://login.microsoftonline.com' client_id = user_client_id or CLIENT_ID return InteractiveBrowserCredential( diff --git a/msgraph/cli/core/commands/client_factory.py b/msgraph/cli/core/commands/client_factory.py index bcd0e1fd..613d6821 100644 --- a/msgraph/cli/core/commands/client_factory.py +++ b/msgraph/cli/core/commands/client_factory.py @@ -7,6 +7,7 @@ from knack.util import CLIError from msgraph.cli.core.authentication import Authentication +from msgraph.cli.core.profile import read_profile from msgraph.core import GraphSession @@ -41,5 +42,13 @@ def get_mgmt_service_client(cli_ctx, client_type, **kwargs): credential = auth.get_credential(auth_record=record) graph_session = GraphSession(credential=credential) - client = client_type({}, session=graph_session) + base_url = None + cloud = read_profile().get('cloud', None) + + if cloud: + base_url = cloud.get('endpoint') + else: + base_url = 'https://graph.microsoft.com/v1.0' + + client = client_type({}, session=graph_session, base_url=base_url) return client diff --git a/msgraph/cli/core/constants.py b/msgraph/cli/core/constants.py index 11e87f99..cf2cb9ab 100644 --- a/msgraph/cli/core/constants.py +++ b/msgraph/cli/core/constants.py @@ -8,7 +8,7 @@ AUTH_RECORD_LOCATION = path.join(Path.home(), '.mg', 'record.txt') PROFILE_LOCATION = path.join(Path.home(), '.mg', 'profile.json') -CLIENT_ID = 'f7218512-c727-4138-9fb9-a0fe2500650c' +CLIENT_ID = '837b13ab-6d14-4dc7-837f-8954cc87fdc0' CLI_COMMON_KWARGS = [ 'min_api', 'max_api', 'resource_type', 'operation_group', 'custom_command_type', 'command_type', From 8f37e1960b05dbcceb264622a2f19de49a8e9a23 Mon Sep 17 00:00:00 2001 From: jobala Date: Thu, 19 Nov 2020 15:19:04 +0300 Subject: [PATCH 11/32] Fix auth-record conflict --- msgraph/cli/core/authentication.py | 7 ++++++- msgraph/cli/core/commands/client_factory.py | 1 + 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/msgraph/cli/core/authentication.py b/msgraph/cli/core/authentication.py index af8e748b..ce89eed4 100644 --- a/msgraph/cli/core/authentication.py +++ b/msgraph/cli/core/authentication.py @@ -48,13 +48,18 @@ def get_credential(self, auth_record=None, user_client_id=None) -> InteractiveBr authority = user_cloud['authority'] if user_cloud else 'https://login.microsoftonline.com' client_id = user_client_id or CLIENT_ID + if auth_record: + return InteractiveBrowserCredential( + enable_persistent_cache=True, + allow_unencrypted_cache=False, + authentication_record=auth_record, + ) return InteractiveBrowserCredential( authority=authority, client_id=client_id, enable_persistent_cache=True, allow_unencrypted_cache=False, - authentication_record=auth_record, ) def _save_auth_record(self, auth_record: AuthenticationRecord): diff --git a/msgraph/cli/core/commands/client_factory.py b/msgraph/cli/core/commands/client_factory.py index 613d6821..ac55db43 100644 --- a/msgraph/cli/core/commands/client_factory.py +++ b/msgraph/cli/core/commands/client_factory.py @@ -47,6 +47,7 @@ def get_mgmt_service_client(cli_ctx, client_type, **kwargs): if cloud: base_url = cloud.get('endpoint') + print(base_url) else: base_url = 'https://graph.microsoft.com/v1.0' From ca2520cf06d53f8069b1851ed54dbd4e926af49c Mon Sep 17 00:00:00 2001 From: jobala Date: Mon, 23 Nov 2020 10:26:10 +0300 Subject: [PATCH 12/32] Add comments --- msgraph/cli/core/authentication.py | 11 ++++++++--- msgraph/cli/core/commands/client_factory.py | 1 - msgraph/cli/core/constants.py | 3 ++- msgraph/cli/core/profile.py | 2 ++ 4 files changed, 12 insertions(+), 5 deletions(-) diff --git a/msgraph/cli/core/authentication.py b/msgraph/cli/core/authentication.py index ce89eed4..812d210b 100644 --- a/msgraph/cli/core/authentication.py +++ b/msgraph/cli/core/authentication.py @@ -6,7 +6,7 @@ from os import path, remove from azure.identity import InteractiveBrowserCredential, AuthenticationRecord -from msgraph.cli.core.constants import AUTH_RECORD_LOCATION, CLIENT_ID +from msgraph.cli.core.constants import AUTH_RECORD_LOCATION, DEFAULT_CLIENT_ID, DEFAULT_AUTHORITY from msgraph.cli.core.exceptions import CLIException from msgraph.cli.core.profile import read_profile @@ -45,9 +45,13 @@ def get_credential(self, auth_record=None, user_client_id=None) -> InteractiveBr ''' profile = read_profile() user_cloud = profile.get('cloud', None) + cloud_authority = user_cloud.get('authority', None) - authority = user_cloud['authority'] if user_cloud else 'https://login.microsoftonline.com' - client_id = user_client_id or CLIENT_ID + authority = cloud_authority or DEFAULT_AUTHORITY + client_id = user_client_id or DEFAULT_CLIENT_ID + + # Once a user is authenticated they get an auth_record object which will have the authority and client_id + # therefore we don't need to pass authority and client_id to InteractiveBrowserCredential. if auth_record: return InteractiveBrowserCredential( enable_persistent_cache=True, @@ -55,6 +59,7 @@ def get_credential(self, auth_record=None, user_client_id=None) -> InteractiveBr authentication_record=auth_record, ) + # Passes authority and client_id when the user doesn't have an auth record return InteractiveBrowserCredential( authority=authority, client_id=client_id, diff --git a/msgraph/cli/core/commands/client_factory.py b/msgraph/cli/core/commands/client_factory.py index ac55db43..613d6821 100644 --- a/msgraph/cli/core/commands/client_factory.py +++ b/msgraph/cli/core/commands/client_factory.py @@ -47,7 +47,6 @@ def get_mgmt_service_client(cli_ctx, client_type, **kwargs): if cloud: base_url = cloud.get('endpoint') - print(base_url) else: base_url = 'https://graph.microsoft.com/v1.0' diff --git a/msgraph/cli/core/constants.py b/msgraph/cli/core/constants.py index cf2cb9ab..c906b945 100644 --- a/msgraph/cli/core/constants.py +++ b/msgraph/cli/core/constants.py @@ -8,7 +8,8 @@ AUTH_RECORD_LOCATION = path.join(Path.home(), '.mg', 'record.txt') PROFILE_LOCATION = path.join(Path.home(), '.mg', 'profile.json') -CLIENT_ID = '837b13ab-6d14-4dc7-837f-8954cc87fdc0' +DEFAULT_CLIENT_ID = '837b13ab-6d14-4dc7-837f-8954cc87fdc0' +DEFAULT_AUTHORITY = 'https://login.microsoftonline.com' CLI_COMMON_KWARGS = [ 'min_api', 'max_api', 'resource_type', 'operation_group', 'custom_command_type', 'command_type', diff --git a/msgraph/cli/core/profile.py b/msgraph/cli/core/profile.py index efc5725d..923e62db 100644 --- a/msgraph/cli/core/profile.py +++ b/msgraph/cli/core/profile.py @@ -11,6 +11,8 @@ def read_profile() -> dict: result = file.read() return json.loads(result) except IOError as ex: + # This error will be thrown if a user has not selected a cloud before. + # Returning an empty dictionary so that the result can be processed by json.loads() return {} From c378e1bda8490c4d94063f9da2719e150cb5d4e3 Mon Sep 17 00:00:00 2001 From: jobala Date: Mon, 23 Nov 2020 10:30:35 +0300 Subject: [PATCH 13/32] Specify version --- msgraph/cli/core/constants.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/msgraph/cli/core/constants.py b/msgraph/cli/core/constants.py index c906b945..85f4c537 100644 --- a/msgraph/cli/core/constants.py +++ b/msgraph/cli/core/constants.py @@ -29,11 +29,11 @@ DEFAULT_CLOUDS = { 'PUBLIC': { - 'endpoint': 'https://graph.microsoft.com', + 'endpoint': 'https://graph.microsoft.com/v1.0', 'authority': 'https://login.microsoftonline.com' }, 'US_GOV_L4': { - 'endpoint': 'https://graph.microsoft.us', + 'endpoint': 'https://graph.microsoft.us/v1.0', 'authority': 'https://login.microsoftonline.us' }, 'US_GOV_L5': { @@ -41,11 +41,11 @@ 'authority': 'https://login.microsoftonline.us' }, 'GERMANY': { - 'endpoint': 'https://graph.microsoft.de', + 'endpoint': 'https://graph.microsoft.de/v1.0', 'authority': 'https://login.microsoftonline.de' }, 'CHINA': { - 'endpoint': 'https://microsoftgraph.chinacloudapi.cn', + 'endpoint': 'https://microsoftgraph.chinacloudapi.cn/v1.0', 'authority': 'https://login.chinacloudapi.cn' } } \ No newline at end of file From e629b7560151ac32ca5ba3ae95562c4cce9157e9 Mon Sep 17 00:00:00 2001 From: jobala Date: Mon, 23 Nov 2020 10:32:18 +0300 Subject: [PATCH 14/32] Improve print message --- msgraph/command_modules/profile/custom.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/msgraph/command_modules/profile/custom.py b/msgraph/command_modules/profile/custom.py index 7f7c40f3..c7b13ed1 100644 --- a/msgraph/command_modules/profile/custom.py +++ b/msgraph/command_modules/profile/custom.py @@ -20,7 +20,8 @@ def select_cloud(): selected = prompt_choice_list('Select a cloud', supported_clouds) profile['cloud'] = DEFAULT_CLOUDS.get(supported_clouds[selected]) write_profile(json.dumps(profile)) - print(f'Selected {supported_clouds[selected]}') + + print(f'Selected {supported_clouds[selected]} cloud') def add_cloud(name: str, endpoint: str, authority: str): From 276d34e8f32f867e0cbbf20ed4ccea9352d3184c Mon Sep 17 00:00:00 2001 From: jobala Date: Tue, 24 Nov 2020 09:52:12 +0300 Subject: [PATCH 15/32] Add default base url constant --- msgraph/cli/core/commands/client_factory.py | 3 ++- msgraph/cli/core/constants.py | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/msgraph/cli/core/commands/client_factory.py b/msgraph/cli/core/commands/client_factory.py index 613d6821..8917bfa3 100644 --- a/msgraph/cli/core/commands/client_factory.py +++ b/msgraph/cli/core/commands/client_factory.py @@ -9,6 +9,7 @@ from msgraph.cli.core.authentication import Authentication from msgraph.cli.core.profile import read_profile from msgraph.core import GraphSession +from msgraph.cli.core.constants import DEFAULT_BASE_URL def resolve_client_arg_name(operation, kwargs): @@ -48,7 +49,7 @@ def get_mgmt_service_client(cli_ctx, client_type, **kwargs): if cloud: base_url = cloud.get('endpoint') else: - base_url = 'https://graph.microsoft.com/v1.0' + base_url = DEFAULT_BASE_URL client = client_type({}, session=graph_session, base_url=base_url) return client diff --git a/msgraph/cli/core/constants.py b/msgraph/cli/core/constants.py index 85f4c537..edb65ff1 100644 --- a/msgraph/cli/core/constants.py +++ b/msgraph/cli/core/constants.py @@ -10,6 +10,7 @@ PROFILE_LOCATION = path.join(Path.home(), '.mg', 'profile.json') DEFAULT_CLIENT_ID = '837b13ab-6d14-4dc7-837f-8954cc87fdc0' DEFAULT_AUTHORITY = 'https://login.microsoftonline.com' +DEFAULT_BASE_URL = 'https://graph.microsoft.com/v1.0' CLI_COMMON_KWARGS = [ 'min_api', 'max_api', 'resource_type', 'operation_group', 'custom_command_type', 'command_type', @@ -37,7 +38,7 @@ 'authority': 'https://login.microsoftonline.us' }, 'US_GOV_L5': { - 'endpoint': 'https://dod-graph.microsoft.us', + 'endpoint': 'https://dod-graph.microsoft.us/v1.0', 'authority': 'https://login.microsoftonline.us' }, 'GERMANY': { From eed4497021a297492fb6339cb1f216f3ef1d4cd9 Mon Sep 17 00:00:00 2001 From: jobala Date: Thu, 26 Nov 2020 10:09:22 +0300 Subject: [PATCH 16/32] Refactor to graph_endpoint and azure_ad_endpoint --- msgraph/cli/core/authentication.py | 2 +- msgraph/cli/core/commands/client_factory.py | 2 +- msgraph/cli/core/constants.py | 20 ++++++++++---------- msgraph/command_modules/profile/custom.py | 8 ++++---- 4 files changed, 16 insertions(+), 16 deletions(-) diff --git a/msgraph/cli/core/authentication.py b/msgraph/cli/core/authentication.py index 812d210b..7c833f2e 100644 --- a/msgraph/cli/core/authentication.py +++ b/msgraph/cli/core/authentication.py @@ -45,7 +45,7 @@ def get_credential(self, auth_record=None, user_client_id=None) -> InteractiveBr ''' profile = read_profile() user_cloud = profile.get('cloud', None) - cloud_authority = user_cloud.get('authority', None) + cloud_authority = user_cloud.get('azure_ad_endpoint', None) authority = cloud_authority or DEFAULT_AUTHORITY client_id = user_client_id or DEFAULT_CLIENT_ID diff --git a/msgraph/cli/core/commands/client_factory.py b/msgraph/cli/core/commands/client_factory.py index 8917bfa3..5ade679f 100644 --- a/msgraph/cli/core/commands/client_factory.py +++ b/msgraph/cli/core/commands/client_factory.py @@ -47,7 +47,7 @@ def get_mgmt_service_client(cli_ctx, client_type, **kwargs): cloud = read_profile().get('cloud', None) if cloud: - base_url = cloud.get('endpoint') + base_url = cloud.get('graph_endpoint') else: base_url = DEFAULT_BASE_URL diff --git a/msgraph/cli/core/constants.py b/msgraph/cli/core/constants.py index edb65ff1..3fc047fb 100644 --- a/msgraph/cli/core/constants.py +++ b/msgraph/cli/core/constants.py @@ -30,23 +30,23 @@ DEFAULT_CLOUDS = { 'PUBLIC': { - 'endpoint': 'https://graph.microsoft.com/v1.0', - 'authority': 'https://login.microsoftonline.com' + 'graph_endpoint': 'https://graph.microsoft.com/v1.0', + 'azure_ad_endpoint': 'https://login.microsoftonline.com' }, 'US_GOV_L4': { - 'endpoint': 'https://graph.microsoft.us/v1.0', - 'authority': 'https://login.microsoftonline.us' + 'graph_endpoint': 'https://graph.microsoft.us/v1.0', + 'azure_ad_endpoint': 'https://login.microsoftonline.us' }, 'US_GOV_L5': { - 'endpoint': 'https://dod-graph.microsoft.us/v1.0', - 'authority': 'https://login.microsoftonline.us' + 'graph_endpoint': 'https://dod-graph.microsoft.us/v1.0', + 'azure_ad_endpoint': 'https://login.microsoftonline.us' }, 'GERMANY': { - 'endpoint': 'https://graph.microsoft.de/v1.0', - 'authority': 'https://login.microsoftonline.de' + 'graph_endpoint': 'https://graph.microsoft.de/v1.0', + 'azure_ad_endpoint': 'https://login.microsoftonline.de' }, 'CHINA': { - 'endpoint': 'https://microsoftgraph.chinacloudapi.cn/v1.0', - 'authority': 'https://login.chinacloudapi.cn' + 'graph_endpoint': 'https://microsoftgraph.chinacloudapi.cn/v1.0', + 'azure_ad_endpoint': 'https://login.chinacloudapi.cn' } } \ No newline at end of file diff --git a/msgraph/command_modules/profile/custom.py b/msgraph/command_modules/profile/custom.py index c7b13ed1..20990741 100644 --- a/msgraph/command_modules/profile/custom.py +++ b/msgraph/command_modules/profile/custom.py @@ -24,10 +24,10 @@ def select_cloud(): print(f'Selected {supported_clouds[selected]} cloud') -def add_cloud(name: str, endpoint: str, authority: str): - _validate(endpoint) +def add_cloud(name: str, graph_endpoint: str, azure_ad_endpoint: str): + _validate(graph_endpoint) - cloud = {name: {'endpoint': endpoint, 'authority': authority}} + cloud = {name: {'graph_endpoint': graph_endpoint, 'azure_ad_endpoint': azure_ad_endpoint}} profile = read_profile() @@ -47,4 +47,4 @@ def _validate(url: str): try: request.urlopen(url) except IOError as error: - raise Exception('Invalid endpoint') \ No newline at end of file + raise Exception('Invalid endpoint') From 10afc6788e3c819c50693e8c2cfb3d15d87a0d3e Mon Sep 17 00:00:00 2001 From: jobala Date: Thu, 26 Nov 2020 10:26:38 +0300 Subject: [PATCH 17/32] Ask devs to update the help file --- msgraph/command_modules/profile/custom.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/msgraph/command_modules/profile/custom.py b/msgraph/command_modules/profile/custom.py index 20990741..25e8070b 100644 --- a/msgraph/command_modules/profile/custom.py +++ b/msgraph/command_modules/profile/custom.py @@ -3,6 +3,9 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- +''' +Update the _help.py file after changing the signature or behavior of functions in this file +''' import json from knack.prompting import prompt_choice_list from msgraph.cli.core.constants import DEFAULT_CLOUDS From f9d5b422b6a83270e877090b115d2bb5a9f7558d Mon Sep 17 00:00:00 2001 From: jobala Date: Thu, 26 Nov 2020 10:51:27 +0300 Subject: [PATCH 18/32] Update login help --- msgraph/cli/core/authentication.py | 10 +++++++--- msgraph/command_modules/authentication/_help.py | 7 +++++-- msgraph/command_modules/authentication/custom.py | 4 ++-- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/msgraph/cli/core/authentication.py b/msgraph/cli/core/authentication.py index 7c833f2e..570264ac 100644 --- a/msgraph/cli/core/authentication.py +++ b/msgraph/cli/core/authentication.py @@ -12,9 +12,9 @@ class Authentication: - def login(self, scopes: [str], client_id=None) -> bool: + def login(self, scopes: [str], client_id=None, tenant_id=None) -> bool: try: - credential = self.get_credential(user_client_id=client_id) + credential = self.get_credential(user_client_id=client_id, tenant_id=tenant_id) auth_record = credential.authenticate(scopes=scopes) if auth_record is None: @@ -36,7 +36,10 @@ def logout(self): # By deleting the authentication record, we logout the user self._delete_auth_record() - def get_credential(self, auth_record=None, user_client_id=None) -> InteractiveBrowserCredential: + def get_credential(self, + auth_record=None, + user_client_id=None, + tenant_id=None) -> InteractiveBrowserCredential: ''' Raises ------ @@ -63,6 +66,7 @@ def get_credential(self, auth_record=None, user_client_id=None) -> InteractiveBr return InteractiveBrowserCredential( authority=authority, client_id=client_id, + tenant_id=tenant_id, enable_persistent_cache=True, allow_unencrypted_cache=False, ) diff --git a/msgraph/command_modules/authentication/_help.py b/msgraph/command_modules/authentication/_help.py index b1dccb26..6395b278 100644 --- a/msgraph/command_modules/authentication/_help.py +++ b/msgraph/command_modules/authentication/_help.py @@ -8,11 +8,14 @@ helps['login'] = """ type: command short-summary: Log in to Microsoft Graph -long-summary: Logs in a user to Microsoft Graph with the specified scopes. You must specify the scopes before you use commands. You will need to log out and log back in to consent to additional scopes. +long-summary: Logs in a user to Microsoft Graph with the specified scopes. You must specify the scopes before you use commands. You will need to log out and log back in to consent to additional scopes. examples: - name: Login in interactively text: > - mg login --scopes "user.read, mail.read" + mg login --scopes "user.read, mail.read" + - name: Sign in to a specific tenant/client + text: > + mg login --scopes "user.read" --client-id --tenant-id """ helps['logout'] = """ diff --git a/msgraph/command_modules/authentication/custom.py b/msgraph/command_modules/authentication/custom.py index 57c1e793..b540cb69 100644 --- a/msgraph/command_modules/authentication/custom.py +++ b/msgraph/command_modules/authentication/custom.py @@ -9,11 +9,11 @@ authentication = Authentication() -def login(scopes: str, client_id=None): +def login(scopes: str, client_id=None, tenant_id=None): # Stripping whitespaces so that users don't have to worry about how # they enter scopes. ie "user.read, mail.read" or "user.read,mail.read" scopes = [scope.strip() for scope in scopes.split(',')] - logged_in = authentication.login(scopes, client_id) + logged_in = authentication.login(scopes, client_id, tenant_id) if not logged_in: raise CLIError('Login failed') From 24ba9f6d97cb38b76e9f2d84da21c79ddc42841e Mon Sep 17 00:00:00 2001 From: jobala Date: Thu, 26 Nov 2020 14:28:19 +0300 Subject: [PATCH 19/32] Refactor adding a cloud --- msgraph/cli/__init__.py | 2 +- msgraph/cli/core/profile.py | 24 +++++++++++++++++++ msgraph/command_modules/profile/custom.py | 28 ++++++++++++++--------- 3 files changed, 42 insertions(+), 12 deletions(-) diff --git a/msgraph/cli/__init__.py b/msgraph/cli/__init__.py index c79f5449..66c2780a 100644 --- a/msgraph/cli/__init__.py +++ b/msgraph/cli/__init__.py @@ -3,4 +3,4 @@ # Licensed under the MIT License. # ------------------------------------ -from .core.profile import read_profile, write_profile \ No newline at end of file +from .core.profile import CloudManager, read_profile, write_profile \ No newline at end of file diff --git a/msgraph/cli/core/profile.py b/msgraph/cli/core/profile.py index 923e62db..f05b6260 100644 --- a/msgraph/cli/core/profile.py +++ b/msgraph/cli/core/profile.py @@ -3,6 +3,30 @@ from msgraph.cli.core.exceptions import CLIException +class CloudManager: + def create_cloud(self, cloud_name, cloud_endpoints): + entry = {cloud_name: cloud_endpoints} + profile = read_profile() + + try: + user_defined_clouds = profile['user_defined_clouds'] + user_defined_clouds.append(entry) + except KeyError: + profile['user_defined_clouds'] = [entry] + + write_profile(json.dumps(profile)) + + def get_current_cloud(self): + pass + + def update_cloud(self): + + pass + + def delete_cloud(self): + pass + + def read_profile() -> dict: result = None diff --git a/msgraph/command_modules/profile/custom.py b/msgraph/command_modules/profile/custom.py index 25e8070b..f97bbbd5 100644 --- a/msgraph/command_modules/profile/custom.py +++ b/msgraph/command_modules/profile/custom.py @@ -9,7 +9,9 @@ import json from knack.prompting import prompt_choice_list from msgraph.cli.core.constants import DEFAULT_CLOUDS -from msgraph.cli import read_profile, write_profile +from msgraph.cli import CloudManager, read_profile, write_profile + +cloud_manager = CloudManager() def select_cloud(): @@ -22,26 +24,30 @@ def select_cloud(): selected = prompt_choice_list('Select a cloud', supported_clouds) profile['cloud'] = DEFAULT_CLOUDS.get(supported_clouds[selected]) - write_profile(json.dumps(profile)) + write_profile(json.dumps(profile)) print(f'Selected {supported_clouds[selected]} cloud') +def current_cloud(): + pass + + def add_cloud(name: str, graph_endpoint: str, azure_ad_endpoint: str): _validate(graph_endpoint) - cloud = {name: {'graph_endpoint': graph_endpoint, 'azure_ad_endpoint': azure_ad_endpoint}} + properties = { + 'name': name, + 'graph_endpoint': graph_endpoint, + 'azure_ad_endpoint': azure_ad_endpoint + } - profile = read_profile() + cloud_manager.create_cloud(name, properties) + print(f'Cloud "{name}" added successfully') - try: - user_defined_clouds = profile['user_defined_clouds'] - user_defined_clouds.append(cloud) - except KeyError: - profile['user_defined_clouds'] = [cloud] - write_profile(json.dumps(profile)) - print(f'Cloud "{name}" added successfully') +def delete_cloud(): + pass def _validate(url: str): From bc715be8dc179b704338cd61a52aeb57ee3b4747 Mon Sep 17 00:00:00 2001 From: jobala Date: Thu, 26 Nov 2020 14:39:41 +0300 Subject: [PATCH 20/32] Add get-current command --- msgraph/cli/core/constants.py | 5 +++++ msgraph/cli/core/profile.py | 12 +++++++----- msgraph/command_modules/profile/__init__.py | 1 + msgraph/command_modules/profile/custom.py | 2 +- 4 files changed, 14 insertions(+), 6 deletions(-) diff --git a/msgraph/cli/core/constants.py b/msgraph/cli/core/constants.py index 3fc047fb..64105052 100644 --- a/msgraph/cli/core/constants.py +++ b/msgraph/cli/core/constants.py @@ -30,22 +30,27 @@ DEFAULT_CLOUDS = { 'PUBLIC': { + 'name': 'PUBLIC', 'graph_endpoint': 'https://graph.microsoft.com/v1.0', 'azure_ad_endpoint': 'https://login.microsoftonline.com' }, 'US_GOV_L4': { + 'name': 'US_GOV_L4', 'graph_endpoint': 'https://graph.microsoft.us/v1.0', 'azure_ad_endpoint': 'https://login.microsoftonline.us' }, 'US_GOV_L5': { + 'name': 'US_GOV_L5', 'graph_endpoint': 'https://dod-graph.microsoft.us/v1.0', 'azure_ad_endpoint': 'https://login.microsoftonline.us' }, 'GERMANY': { + 'name': 'GERMANY', 'graph_endpoint': 'https://graph.microsoft.de/v1.0', 'azure_ad_endpoint': 'https://login.microsoftonline.de' }, 'CHINA': { + 'name': 'CHINA', 'graph_endpoint': 'https://microsoftgraph.chinacloudapi.cn/v1.0', 'azure_ad_endpoint': 'https://login.chinacloudapi.cn' } diff --git a/msgraph/cli/core/profile.py b/msgraph/cli/core/profile.py index f05b6260..6e7ad6e9 100644 --- a/msgraph/cli/core/profile.py +++ b/msgraph/cli/core/profile.py @@ -4,20 +4,22 @@ class CloudManager: + def __init__(self): + self.profile = read_profile() + def create_cloud(self, cloud_name, cloud_endpoints): entry = {cloud_name: cloud_endpoints} - profile = read_profile() try: - user_defined_clouds = profile['user_defined_clouds'] + user_defined_clouds = self.profile['user_defined_clouds'] user_defined_clouds.append(entry) except KeyError: - profile['user_defined_clouds'] = [entry] + self.profile['user_defined_clouds'] = [entry] - write_profile(json.dumps(profile)) + write_profile(json.dumps(self.profile)) def get_current_cloud(self): - pass + return self.profile.get('cloud', None) def update_cloud(self): diff --git a/msgraph/command_modules/profile/__init__.py b/msgraph/command_modules/profile/__init__.py index 2b84bc51..acca948f 100644 --- a/msgraph/command_modules/profile/__init__.py +++ b/msgraph/command_modules/profile/__init__.py @@ -22,6 +22,7 @@ def load_command_table(self, args): with self.command_group('cloud', command_type) as group: group.command('select', 'select_cloud') group.command('add', 'add_cloud') + group.command('get-current', 'current_cloud') return self.command_table diff --git a/msgraph/command_modules/profile/custom.py b/msgraph/command_modules/profile/custom.py index f97bbbd5..f19c5967 100644 --- a/msgraph/command_modules/profile/custom.py +++ b/msgraph/command_modules/profile/custom.py @@ -30,7 +30,7 @@ def select_cloud(): def current_cloud(): - pass + return cloud_manager.get_current_cloud() or DEFAULT_CLOUDS['PUBLIC'] def add_cloud(name: str, graph_endpoint: str, azure_ad_endpoint: str): From 21b584b25dbb19b7d759d77b9aea61f731ef3261 Mon Sep 17 00:00:00 2001 From: jobala Date: Thu, 26 Nov 2020 15:39:06 +0300 Subject: [PATCH 21/32] Add support for deleting clouds --- msgraph/cli/core/profile.py | 13 ++++++++++--- msgraph/command_modules/profile/__init__.py | 1 + msgraph/command_modules/profile/custom.py | 5 +++-- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/msgraph/cli/core/profile.py b/msgraph/cli/core/profile.py index 6e7ad6e9..5bb34b7a 100644 --- a/msgraph/cli/core/profile.py +++ b/msgraph/cli/core/profile.py @@ -18,15 +18,22 @@ def create_cloud(self, cloud_name, cloud_endpoints): write_profile(json.dumps(self.profile)) - def get_current_cloud(self): + def get_current_cloud(self) -> dict: return self.profile.get('cloud', None) def update_cloud(self): pass - def delete_cloud(self): - pass + def delete_cloud(self, name: str): + result = [] + + for cloud in self.profile['user_defined_clouds']: + if name not in cloud.keys(): + result.append(cloud) + + self.profile['user_defined_clouds'] = result + write_profile(json.dumps(self.profile)) def read_profile() -> dict: diff --git a/msgraph/command_modules/profile/__init__.py b/msgraph/command_modules/profile/__init__.py index acca948f..22a215a7 100644 --- a/msgraph/command_modules/profile/__init__.py +++ b/msgraph/command_modules/profile/__init__.py @@ -23,6 +23,7 @@ def load_command_table(self, args): group.command('select', 'select_cloud') group.command('add', 'add_cloud') group.command('get-current', 'current_cloud') + group.command('delete', 'delete_cloud') return self.command_table diff --git a/msgraph/command_modules/profile/custom.py b/msgraph/command_modules/profile/custom.py index f19c5967..7264fa32 100644 --- a/msgraph/command_modules/profile/custom.py +++ b/msgraph/command_modules/profile/custom.py @@ -46,8 +46,9 @@ def add_cloud(name: str, graph_endpoint: str, azure_ad_endpoint: str): print(f'Cloud "{name}" added successfully') -def delete_cloud(): - pass +def delete_cloud(name: str): + cloud_manager.delete_cloud(name) + print(f'Cloud "{name}" deleted successfully') def _validate(url: str): From afce461d6e079ebed3f7ab0b218793a2fe8811e1 Mon Sep 17 00:00:00 2001 From: jobala Date: Thu, 26 Nov 2020 15:59:46 +0300 Subject: [PATCH 22/32] Update help --- msgraph/command_modules/profile/__init__.py | 2 +- msgraph/command_modules/profile/_help.py | 22 +++++++++++++++++++-- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/msgraph/command_modules/profile/__init__.py b/msgraph/command_modules/profile/__init__.py index 22a215a7..be5aa0b8 100644 --- a/msgraph/command_modules/profile/__init__.py +++ b/msgraph/command_modules/profile/__init__.py @@ -22,7 +22,7 @@ def load_command_table(self, args): with self.command_group('cloud', command_type) as group: group.command('select', 'select_cloud') group.command('add', 'add_cloud') - group.command('get-current', 'current_cloud') + group.command('show-current', 'current_cloud') group.command('delete', 'delete_cloud') return self.command_table diff --git a/msgraph/command_modules/profile/_help.py b/msgraph/command_modules/profile/_help.py index 13959d00..23c9c3f2 100644 --- a/msgraph/command_modules/profile/_help.py +++ b/msgraph/command_modules/profile/_help.py @@ -18,13 +18,31 @@ type: string short-summary: Cloud's name long-summary: The cloud's name is shown in the list of clouds when a user runs mg cloud select. - - name: --endpoint + - name: --graph-endpoint type: string short-summary: Cloud's endpoint - - name: --authority + - name: --azure-ad-endpoint short-summary: Cloud's authentication endpoint examples: - name: Add a new cloud text: > mg cloud add --name CUSTOM_CLOUD --endpoint https://graph.microsoft.com --authority https://graph.microsoftonline.com +""" + +helps['cloud show-current'] = """ +type: command +short-summary: Show current cloud +""" + +helps['cloud delete'] = """ +type: command +short-summary: Deletes a user defined cloud +parameters: + - name: --name + type: string + short-summary: Cloud to delete +examples: + - name: Delete cloud + text: > + mg cloud delete --name CUSTOM_CLOUD """ \ No newline at end of file From a8eba11919b75647ba33ffcdf82cfe2e22120484 Mon Sep 17 00:00:00 2001 From: jobala Date: Fri, 27 Nov 2020 15:47:35 +0300 Subject: [PATCH 23/32] Show graph and azure_ad_endpoints when selecting a cloud --- msgraph/cli/core/profile.py | 22 +++++++++++---- msgraph/command_modules/profile/custom.py | 33 +++++++++++++---------- 2 files changed, 36 insertions(+), 19 deletions(-) diff --git a/msgraph/cli/core/profile.py b/msgraph/cli/core/profile.py index 5bb34b7a..cfe613a7 100644 --- a/msgraph/cli/core/profile.py +++ b/msgraph/cli/core/profile.py @@ -1,5 +1,5 @@ import json -from msgraph.cli.core.constants import PROFILE_LOCATION +from msgraph.cli.core.constants import PROFILE_LOCATION, DEFAULT_CLOUDS from msgraph.cli.core.exceptions import CLIException @@ -7,6 +7,14 @@ class CloudManager: def __init__(self): self.profile = read_profile() + def get_clouds(self) -> dict: + user_defined_clouds = self.profile.get('user_defined_clouds', {}) + supported_clouds = DEFAULT_CLOUDS + + for cloud in user_defined_clouds: + supported_clouds.update(cloud) + return supported_clouds + def create_cloud(self, cloud_name, cloud_endpoints): entry = {cloud_name: cloud_endpoints} @@ -16,7 +24,7 @@ def create_cloud(self, cloud_name, cloud_endpoints): except KeyError: self.profile['user_defined_clouds'] = [entry] - write_profile(json.dumps(self.profile)) + write_profile(self.profile) def get_current_cloud(self) -> dict: return self.profile.get('cloud', None) @@ -33,7 +41,11 @@ def delete_cloud(self, name: str): result.append(cloud) self.profile['user_defined_clouds'] = result - write_profile(json.dumps(self.profile)) + write_profile(self.profile) + + def set_current_cloud(self, name: str): + self.profile['cloud'] = self.get_clouds().get(name) + write_profile(self.profile) def read_profile() -> dict: @@ -49,9 +61,9 @@ def read_profile() -> dict: return {} -def write_profile(profile: str): +def write_profile(profile: dict): try: with open(PROFILE_LOCATION, 'w') as file: - file.write(profile) + file.write(json.dumps(profile)) except IOError as ex: raise CLIException('Selected cloud was not set, CLI will use the PublicCLoud') from ex \ No newline at end of file diff --git a/msgraph/command_modules/profile/custom.py b/msgraph/command_modules/profile/custom.py index 7264fa32..23191744 100644 --- a/msgraph/command_modules/profile/custom.py +++ b/msgraph/command_modules/profile/custom.py @@ -6,27 +6,32 @@ ''' Update the _help.py file after changing the signature or behavior of functions in this file ''' -import json from knack.prompting import prompt_choice_list from msgraph.cli.core.constants import DEFAULT_CLOUDS -from msgraph.cli import CloudManager, read_profile, write_profile +from msgraph.cli import CloudManager cloud_manager = CloudManager() def select_cloud(): - profile = read_profile() - user_defined_clouds = profile.get('user_defined_clouds', {}) - - for cloud in user_defined_clouds: - DEFAULT_CLOUDS.update(cloud) - supported_clouds = list(DEFAULT_CLOUDS.keys()) - - selected = prompt_choice_list('Select a cloud', supported_clouds) - profile['cloud'] = DEFAULT_CLOUDS.get(supported_clouds[selected]) - - write_profile(json.dumps(profile)) - print(f'Selected {supported_clouds[selected]} cloud') + supported_clouds = cloud_manager.get_clouds() + formatted = [] + + for cloud_name in supported_clouds: + cloud = supported_clouds[cloud_name] + formatted.append({ + 'name': + cloud.get('name'), + 'desc': + f"""Graph Endpoint: {cloud.get('graph_endpoint')} - Azure AD Endpoint: {cloud.get('azure_ad_endpoint')} + """ + }) + + selected = prompt_choice_list('Select a cloud \n', formatted) + name = formatted[selected].get('name') + + cloud_manager.set_current_cloud(name) + print(f'{name} cloud selected') def current_cloud(): From 6dbd50557a62e84f65e33c396c26bd32c05854d4 Mon Sep 17 00:00:00 2001 From: jobala Date: Fri, 27 Nov 2020 15:50:53 +0300 Subject: [PATCH 24/32] Move CloudManager to the profile module --- msgraph/cli/core/profile.py | 47 +------------------ .../command_modules/profile/_cloud_manager.py | 47 +++++++++++++++++++ msgraph/command_modules/profile/custom.py | 2 +- 3 files changed, 49 insertions(+), 47 deletions(-) create mode 100644 msgraph/command_modules/profile/_cloud_manager.py diff --git a/msgraph/cli/core/profile.py b/msgraph/cli/core/profile.py index cfe613a7..ae5d2df4 100644 --- a/msgraph/cli/core/profile.py +++ b/msgraph/cli/core/profile.py @@ -1,53 +1,8 @@ import json -from msgraph.cli.core.constants import PROFILE_LOCATION, DEFAULT_CLOUDS +from msgraph.cli.core.constants import PROFILE_LOCATION from msgraph.cli.core.exceptions import CLIException -class CloudManager: - def __init__(self): - self.profile = read_profile() - - def get_clouds(self) -> dict: - user_defined_clouds = self.profile.get('user_defined_clouds', {}) - supported_clouds = DEFAULT_CLOUDS - - for cloud in user_defined_clouds: - supported_clouds.update(cloud) - return supported_clouds - - def create_cloud(self, cloud_name, cloud_endpoints): - entry = {cloud_name: cloud_endpoints} - - try: - user_defined_clouds = self.profile['user_defined_clouds'] - user_defined_clouds.append(entry) - except KeyError: - self.profile['user_defined_clouds'] = [entry] - - write_profile(self.profile) - - def get_current_cloud(self) -> dict: - return self.profile.get('cloud', None) - - def update_cloud(self): - - pass - - def delete_cloud(self, name: str): - result = [] - - for cloud in self.profile['user_defined_clouds']: - if name not in cloud.keys(): - result.append(cloud) - - self.profile['user_defined_clouds'] = result - write_profile(self.profile) - - def set_current_cloud(self, name: str): - self.profile['cloud'] = self.get_clouds().get(name) - write_profile(self.profile) - - def read_profile() -> dict: result = None diff --git a/msgraph/command_modules/profile/_cloud_manager.py b/msgraph/command_modules/profile/_cloud_manager.py new file mode 100644 index 00000000..0570772a --- /dev/null +++ b/msgraph/command_modules/profile/_cloud_manager.py @@ -0,0 +1,47 @@ +from msgraph.cli import read_profile, write_profile +from msgraph.cli.core.constants import DEFAULT_CLOUDS + + +class CloudManager: + def __init__(self): + self.profile = read_profile() + + def get_clouds(self) -> dict: + user_defined_clouds = self.profile.get('user_defined_clouds', {}) + supported_clouds = DEFAULT_CLOUDS + + for cloud in user_defined_clouds: + supported_clouds.update(cloud) + return supported_clouds + + def create_cloud(self, cloud_name, cloud_endpoints): + entry = {cloud_name: cloud_endpoints} + + try: + user_defined_clouds = self.profile['user_defined_clouds'] + user_defined_clouds.append(entry) + except KeyError: + self.profile['user_defined_clouds'] = [entry] + + write_profile(self.profile) + + def get_current_cloud(self) -> dict: + return self.profile.get('cloud', None) + + def update_cloud(self): + + pass + + def delete_cloud(self, name: str): + result = [] + + for cloud in self.profile['user_defined_clouds']: + if name not in cloud.keys(): + result.append(cloud) + + self.profile['user_defined_clouds'] = result + write_profile(self.profile) + + def set_current_cloud(self, name: str): + self.profile['cloud'] = self.get_clouds().get(name) + write_profile(self.profile) diff --git a/msgraph/command_modules/profile/custom.py b/msgraph/command_modules/profile/custom.py index 23191744..57983614 100644 --- a/msgraph/command_modules/profile/custom.py +++ b/msgraph/command_modules/profile/custom.py @@ -8,7 +8,7 @@ ''' from knack.prompting import prompt_choice_list from msgraph.cli.core.constants import DEFAULT_CLOUDS -from msgraph.cli import CloudManager +from ._cloud_manager import CloudManager cloud_manager = CloudManager() From 741d1a945835bb1971400cbc4d5c1a7c183dc515 Mon Sep 17 00:00:00 2001 From: jobala Date: Fri, 27 Nov 2020 19:20:17 +0300 Subject: [PATCH 25/32] Fixes import error --- msgraph/cli/__init__.py | 2 +- msgraph/command_modules/profile/_cloud_manager.py | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/msgraph/cli/__init__.py b/msgraph/cli/__init__.py index 66c2780a..4a09d9ec 100644 --- a/msgraph/cli/__init__.py +++ b/msgraph/cli/__init__.py @@ -3,4 +3,4 @@ # Licensed under the MIT License. # ------------------------------------ -from .core.profile import CloudManager, read_profile, write_profile \ No newline at end of file +from .core.profile import read_profile, write_profile diff --git a/msgraph/command_modules/profile/_cloud_manager.py b/msgraph/command_modules/profile/_cloud_manager.py index 0570772a..422248f3 100644 --- a/msgraph/command_modules/profile/_cloud_manager.py +++ b/msgraph/command_modules/profile/_cloud_manager.py @@ -1,3 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + from msgraph.cli import read_profile, write_profile from msgraph.cli.core.constants import DEFAULT_CLOUDS @@ -29,7 +35,6 @@ def get_current_cloud(self) -> dict: return self.profile.get('cloud', None) def update_cloud(self): - pass def delete_cloud(self, name: str): From 875770ac7a862081ad12bd492a859b510cff71e9 Mon Sep 17 00:00:00 2001 From: jobala Date: Mon, 30 Nov 2020 14:18:54 +0300 Subject: [PATCH 26/32] Add update command help information --- msgraph/command_modules/profile/__init__.py | 3 +- .../command_modules/profile/_cloud_manager.py | 26 +++++++++- msgraph/command_modules/profile/_help.py | 43 +++++++++++---- msgraph/command_modules/profile/custom.py | 52 +++++++++++++------ 4 files changed, 94 insertions(+), 30 deletions(-) diff --git a/msgraph/command_modules/profile/__init__.py b/msgraph/command_modules/profile/__init__.py index be5aa0b8..d9b6d12d 100644 --- a/msgraph/command_modules/profile/__init__.py +++ b/msgraph/command_modules/profile/__init__.py @@ -23,9 +23,10 @@ def load_command_table(self, args): group.command('select', 'select_cloud') group.command('add', 'add_cloud') group.command('show-current', 'current_cloud') + group.command('update', 'update_cloud') group.command('delete', 'delete_cloud') return self.command_table -COMMAND_LOADER_CLS = ProfileCommandsLoader \ No newline at end of file +COMMAND_LOADER_CLS = ProfileCommandsLoader diff --git a/msgraph/command_modules/profile/_cloud_manager.py b/msgraph/command_modules/profile/_cloud_manager.py index 422248f3..e331d30c 100644 --- a/msgraph/command_modules/profile/_cloud_manager.py +++ b/msgraph/command_modules/profile/_cloud_manager.py @@ -34,8 +34,30 @@ def create_cloud(self, cloud_name, cloud_endpoints): def get_current_cloud(self) -> dict: return self.profile.get('cloud', None) - def update_cloud(self): - pass + def update_cloud(self, cloud_name: str, props: dict): + updated = False + user_defined_clouds = self.profile.get('user_defined_clouds') + + # Search for the cloud to update in user defined clouds + for index, cloud in enumerate(user_defined_clouds): + found = cloud.get(cloud_name, None) + + if found: + cloud_to_update = cloud[cloud_name] + cloud_to_update.update(props) + + # Remove the old cloud and replace it with the updated cloud + user_defined_clouds.pop(index) + user_defined_clouds.insert(index, {cloud_to_update['name']: cloud_to_update}) + + updated = True + self.profile['user_defined_clouds'] = user_defined_clouds + write_profile(self.profile) + + # No need to keep looking for the cloud + break + + return updated def delete_cloud(self, name: str): result = [] diff --git a/msgraph/command_modules/profile/_help.py b/msgraph/command_modules/profile/_help.py index 23c9c3f2..00d76176 100644 --- a/msgraph/command_modules/profile/_help.py +++ b/msgraph/command_modules/profile/_help.py @@ -10,6 +10,24 @@ short-summary: Select a cloud from supported clouds. """ +helps['cloud show-current'] = """ +type: command +short-summary: Show current cloud +""" + +helps['cloud delete'] = """ +type: command +short-summary: Deletes a user defined cloud +parameters: + - name: --name + type: string + short-summary: Cloud to delete +examples: + - name: Delete cloud + text: > + mg cloud delete --name CUSTOM_CLOUD +""" + helps['cloud add'] = """ type: command short-summary: Add a custom cloud @@ -29,20 +47,23 @@ mg cloud add --name CUSTOM_CLOUD --endpoint https://graph.microsoft.com --authority https://graph.microsoftonline.com """ -helps['cloud show-current'] = """ +helps['cloud update'] = """ type: command -short-summary: Show current cloud -""" - -helps['cloud delete'] = """ -type: command -short-summary: Deletes a user defined cloud +short-summary: update a user defined cloud parameters: + - name: --cloud + type: string + short-summary: Name of user defined cloud to update - name: --name type: string - short-summary: Cloud to delete + short-summary: Cloud's name + - name: --graph-endpoint + type: string + short-summary: Cloud's endpoint + - name: --azure-ad-endpoint + short-summary: Cloud's authentication endpoint examples: - - name: Delete cloud + - name: Update a user defined cloud text: > - mg cloud delete --name CUSTOM_CLOUD -""" \ No newline at end of file + mg cloud update --cloud CUSTOM_CLOUD --name UPDATED_NAME +""" diff --git a/msgraph/command_modules/profile/custom.py b/msgraph/command_modules/profile/custom.py index 57983614..76721846 100644 --- a/msgraph/command_modules/profile/custom.py +++ b/msgraph/command_modules/profile/custom.py @@ -13,6 +13,28 @@ cloud_manager = CloudManager() +def current_cloud(): + return cloud_manager.get_current_cloud() or DEFAULT_CLOUDS['PUBLIC'] + + +def delete_cloud(name: str): + cloud_manager.delete_cloud(name) + print(f'Cloud "{name}" deleted successfully') + + +def add_cloud(name: str, graph_endpoint: str, azure_ad_endpoint: str): + _validate(graph_endpoint) + + properties = { + 'name': name, + 'graph_endpoint': graph_endpoint, + 'azure_ad_endpoint': azure_ad_endpoint + } + + cloud_manager.create_cloud(name, properties) + print(f'Cloud "{name}" added successfully') + + def select_cloud(): supported_clouds = cloud_manager.get_clouds() formatted = [] @@ -34,26 +56,24 @@ def select_cloud(): print(f'{name} cloud selected') -def current_cloud(): - return cloud_manager.get_current_cloud() or DEFAULT_CLOUDS['PUBLIC'] +def update_cloud(cloud: str, name=None, graph_endpoint=None, azure_ad_endpoint=None): + update_props = {} -def add_cloud(name: str, graph_endpoint: str, azure_ad_endpoint: str): - _validate(graph_endpoint) + if name: + update_props.update({'name': name}) + if graph_endpoint: + _validate(graph_endpoint) + update_props.update({'graph_endpoint': graph_endpoint}) + if azure_ad_endpoint: + update_props.update({'azure_ad_endpoint': azure_ad_endpoint}) - properties = { - 'name': name, - 'graph_endpoint': graph_endpoint, - 'azure_ad_endpoint': azure_ad_endpoint - } - - cloud_manager.create_cloud(name, properties) - print(f'Cloud "{name}" added successfully') + updated = cloud_manager.update_cloud(cloud, update_props) - -def delete_cloud(name: str): - cloud_manager.delete_cloud(name) - print(f'Cloud "{name}" deleted successfully') + if updated: + print(f'{cloud} updated successfully') + else: + print(f'{cloud} does not exist') def _validate(url: str): From 4de033db8c11bcee0ad8a11c602a1466be2a188d Mon Sep 17 00:00:00 2001 From: jobala Date: Thu, 3 Dec 2020 00:35:35 +0300 Subject: [PATCH 27/32] Raise CLI errors when a cloud is current or doesn't exist --- msgraph/command_modules/profile/_cloud_manager.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/msgraph/command_modules/profile/_cloud_manager.py b/msgraph/command_modules/profile/_cloud_manager.py index e331d30c..f05574df 100644 --- a/msgraph/command_modules/profile/_cloud_manager.py +++ b/msgraph/command_modules/profile/_cloud_manager.py @@ -6,6 +6,7 @@ from msgraph.cli import read_profile, write_profile from msgraph.cli.core.constants import DEFAULT_CLOUDS +from msgraph.cli.core.exceptions import CLIError class CloudManager: @@ -61,6 +62,15 @@ def update_cloud(self, cloud_name: str, props: dict): def delete_cloud(self, name: str): result = [] + current_cloud = self.profile.get('cloud', None) + + # throw an error if a user attempts to delete a user defined cloud + if current_cloud and name == current_cloud['name']: + raise CLIError(f'The cloud "{name}" could not be deleted because it is a current cloud') + + # throw an error if the cloud does not exit + if name not in self.profile['user_defined_clouds']: + raise CLIError(f'The cloud "{name}" is not a user defined cloud') for cloud in self.profile['user_defined_clouds']: if name not in cloud.keys(): From 3aa5c3ee04791a44fe0521d61f4d5596a57c688d Mon Sep 17 00:00:00 2001 From: jobala Date: Thu, 3 Dec 2020 00:42:48 +0300 Subject: [PATCH 28/32] Parameterizes error message in write_profile --- msgraph/cli/core/profile.py | 6 ++++-- msgraph/command_modules/profile/_cloud_manager.py | 11 +++++++---- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/msgraph/cli/core/profile.py b/msgraph/cli/core/profile.py index ae5d2df4..b3491882 100644 --- a/msgraph/cli/core/profile.py +++ b/msgraph/cli/core/profile.py @@ -16,9 +16,11 @@ def read_profile() -> dict: return {} -def write_profile(profile: dict): +def write_profile(profile: dict, error_msg: str): + #TODO: Parameterize the error message + try: with open(PROFILE_LOCATION, 'w') as file: file.write(json.dumps(profile)) except IOError as ex: - raise CLIException('Selected cloud was not set, CLI will use the PublicCLoud') from ex \ No newline at end of file + raise CLIException(error_msg) from ex \ No newline at end of file diff --git a/msgraph/command_modules/profile/_cloud_manager.py b/msgraph/command_modules/profile/_cloud_manager.py index f05574df..11f00607 100644 --- a/msgraph/command_modules/profile/_cloud_manager.py +++ b/msgraph/command_modules/profile/_cloud_manager.py @@ -30,7 +30,7 @@ def create_cloud(self, cloud_name, cloud_endpoints): except KeyError: self.profile['user_defined_clouds'] = [entry] - write_profile(self.profile) + write_profile(self.profile, 'An error occured while creating the cloud.') def get_current_cloud(self) -> dict: return self.profile.get('cloud', None) @@ -53,7 +53,7 @@ def update_cloud(self, cloud_name: str, props: dict): updated = True self.profile['user_defined_clouds'] = user_defined_clouds - write_profile(self.profile) + write_profile(self.profile, error_msg='An error occured while updating the cloud') # No need to keep looking for the cloud break @@ -77,8 +77,11 @@ def delete_cloud(self, name: str): result.append(cloud) self.profile['user_defined_clouds'] = result - write_profile(self.profile) + write_profile(self.profile, error_msg='An error occured while deleting the cloud') def set_current_cloud(self, name: str): self.profile['cloud'] = self.get_clouds().get(name) - write_profile(self.profile) + write_profile( + self.profile, + error_msg= + 'An error occured while setting the selected cloud, the CLI will use the PUBLIC cloud') From 5bf95a7176121915ae73510498ba438d12000864 Mon Sep 17 00:00:00 2001 From: jobala Date: Thu, 3 Dec 2020 00:44:56 +0300 Subject: [PATCH 29/32] Improve error message --- msgraph/command_modules/profile/_cloud_manager.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/msgraph/command_modules/profile/_cloud_manager.py b/msgraph/command_modules/profile/_cloud_manager.py index 11f00607..f3b7e168 100644 --- a/msgraph/command_modules/profile/_cloud_manager.py +++ b/msgraph/command_modules/profile/_cloud_manager.py @@ -53,7 +53,9 @@ def update_cloud(self, cloud_name: str, props: dict): updated = True self.profile['user_defined_clouds'] = user_defined_clouds - write_profile(self.profile, error_msg='An error occured while updating the cloud') + write_profile( + self.profile, + error_msg=f'An error occured while updating the "{cloud_name}" cloud') # No need to keep looking for the cloud break @@ -77,7 +79,7 @@ def delete_cloud(self, name: str): result.append(cloud) self.profile['user_defined_clouds'] = result - write_profile(self.profile, error_msg='An error occured while deleting the cloud') + write_profile(self.profile, error_msg=f'An error occured while deleting the "{name}" cloud') def set_current_cloud(self, name: str): self.profile['cloud'] = self.get_clouds().get(name) From 7192125d425990e433e77b6f84ba16efa5b7a1f7 Mon Sep 17 00:00:00 2001 From: jobala Date: Thu, 3 Dec 2020 00:50:16 +0300 Subject: [PATCH 30/32] Document CloudManager --- msgraph/command_modules/profile/_cloud_manager.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/msgraph/command_modules/profile/_cloud_manager.py b/msgraph/command_modules/profile/_cloud_manager.py index f3b7e168..9115338d 100644 --- a/msgraph/command_modules/profile/_cloud_manager.py +++ b/msgraph/command_modules/profile/_cloud_manager.py @@ -10,6 +10,9 @@ class CloudManager: + '''This class adds support for managing MicrosoftGraph and user defined clouds + List of supported Microsoft Graph clouds: https://docs.microsoft.com/en-us/graph/deployments + ''' def __init__(self): self.profile = read_profile() From 640089963342cd0d8932ab00921c7de56b03ac4b Mon Sep 17 00:00:00 2001 From: jobala Date: Thu, 3 Dec 2020 01:19:43 +0300 Subject: [PATCH 31/32] Add instructions on how to change and show the current cloud --- msgraph/command_modules/profile/_cloud_manager.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/msgraph/command_modules/profile/_cloud_manager.py b/msgraph/command_modules/profile/_cloud_manager.py index 9115338d..4e2bdaa0 100644 --- a/msgraph/command_modules/profile/_cloud_manager.py +++ b/msgraph/command_modules/profile/_cloud_manager.py @@ -71,9 +71,13 @@ def delete_cloud(self, name: str): # throw an error if a user attempts to delete a user defined cloud if current_cloud and name == current_cloud['name']: - raise CLIError(f'The cloud "{name}" could not be deleted because it is a current cloud') + raise CLIError(f'''The cloud "{name}" could not be deleted because it is a current cloud - # throw an error if the cloud does not exit +To see the current cloud run mg cloud show-current +To change to a different cloud run mg cloud select +''') + + # throw an error if the cloud is not a user defined cloud if name not in self.profile['user_defined_clouds']: raise CLIError(f'The cloud "{name}" is not a user defined cloud') From 3cb316f05288177ef7b4f76ee7fe27ff53eb601c Mon Sep 17 00:00:00 2001 From: jobala Date: Thu, 3 Dec 2020 01:20:58 +0300 Subject: [PATCH 32/32] Fix comment --- msgraph/command_modules/profile/_cloud_manager.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/msgraph/command_modules/profile/_cloud_manager.py b/msgraph/command_modules/profile/_cloud_manager.py index 4e2bdaa0..f2e92969 100644 --- a/msgraph/command_modules/profile/_cloud_manager.py +++ b/msgraph/command_modules/profile/_cloud_manager.py @@ -69,7 +69,7 @@ def delete_cloud(self, name: str): result = [] current_cloud = self.profile.get('cloud', None) - # throw an error if a user attempts to delete a user defined cloud + # throw an error if a user attempts to delete a current cloud if current_cloud and name == current_cloud['name']: raise CLIError(f'''The cloud "{name}" could not be deleted because it is a current cloud