Skip to content
This repository was archived by the owner on May 17, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
40c816b
Add cloud commands
jobala Nov 16, 2020
eb0a7a6
Move profile
jobala Nov 16, 2020
309ccbc
Supports selecting a cloud
jobala Nov 16, 2020
3823f8a
Remove list clouds
jobala Nov 17, 2020
ec9388b
Supports user defined clouds
jobala Nov 17, 2020
816a37d
Add help information
jobala Nov 17, 2020
be657ca
Move constants into msgraph.cli.core
jobala Nov 17, 2020
e82f31d
Validate endpoint
jobala Nov 18, 2020
6c25da7
Accept user provided client_id and read authority from user profile
jobala Nov 18, 2020
d9c08a5
Use cloud endpoint as base url
jobala Nov 19, 2020
8f37e19
Fix auth-record conflict
jobala Nov 19, 2020
ca2520c
Add comments
jobala Nov 23, 2020
c378e1b
Specify version
jobala Nov 23, 2020
e629b75
Improve print message
jobala Nov 23, 2020
276d34e
Add default base url constant
jobala Nov 24, 2020
eed4497
Refactor to graph_endpoint and azure_ad_endpoint
jobala Nov 26, 2020
10afc67
Ask devs to update the help file
jobala Nov 26, 2020
f9d5b42
Update login help
jobala Nov 26, 2020
24ba9f6
Refactor adding a cloud
jobala Nov 26, 2020
bc715be
Add get-current command
jobala Nov 26, 2020
21b584b
Add support for deleting clouds
jobala Nov 26, 2020
afce461
Update help
jobala Nov 26, 2020
a8eba11
Show graph and azure_ad_endpoints when selecting a cloud
jobala Nov 27, 2020
6dbd505
Move CloudManager to the profile module
jobala Nov 27, 2020
741d1a9
Fixes import error
jobala Nov 27, 2020
875770a
Add update command help information
jobala Nov 30, 2020
4de033d
Raise CLI errors when a cloud is current or doesn't exist
jobala Dec 2, 2020
3aa5c3e
Parameterizes error message in write_profile
jobala Dec 2, 2020
5bf95a7
Improve error message
jobala Dec 2, 2020
7192125
Document CloudManager
jobala Dec 2, 2020
6400899
Add instructions on how to change and show the current cloud
jobala Dec 2, 2020
3cb316f
Fix comment
jobala Dec 2, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions msgraph/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------

from .core.profile import read_profile, write_profile
37 changes: 29 additions & 8 deletions msgraph/cli/core/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@
# 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.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


class Authentication:
def login(self, scopes: [str]) -> bool:
def login(self, scopes: [str], client_id=None, tenant_id=None) -> bool:
try:
credential = self.get_credential()
credential = self.get_credential(user_client_id=client_id, tenant_id=tenant_id)
auth_record = credential.authenticate(scopes=scopes)

if auth_record is None:
Expand All @@ -36,18 +36,39 @@ 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,
tenant_id=None) -> InteractiveBrowserCredential:
'''
Raises
------
ValueError
If PyGObject is not installed in the host Linux OS.
'''
profile = read_profile()
user_cloud = profile.get('cloud', 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

# 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,
allow_unencrypted_cache=False,
authentication_record=auth_record,
)

# Passes authority and client_id when the user doesn't have an auth record
return InteractiveBrowserCredential(
client_id=CLIENT_ID,
authority=authority,
client_id=client_id,
tenant_id=tenant_id,
enable_persistent_cache=True,
allow_unencrypted_cache=False,
authentication_record=auth_record,
)

def _save_auth_record(self, auth_record: AuthenticationRecord):
Expand Down
12 changes: 11 additions & 1 deletion msgraph/cli/core/commands/client_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
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
from msgraph.cli.core.constants import DEFAULT_BASE_URL


def resolve_client_arg_name(operation, kwargs):
Expand Down Expand Up @@ -41,5 +43,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('graph_endpoint')
else:
base_url = DEFAULT_BASE_URL

client = client_type({}, session=graph_session, base_url=base_url)
return client
33 changes: 32 additions & 1 deletion msgraph/cli/core/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@
from os import path

AUTH_RECORD_LOCATION = path.join(Path.home(), '.mg', 'record.txt')
CLIENT_ID = 'f7218512-c727-4138-9fb9-a0fe2500650c'
PROFILE_LOCATION = path.join(Path.home(), '.mg', 'profile.json')
DEFAULT_CLIENT_ID = '837b13ab-6d14-4dc7-837f-8954cc87fdc0'
Comment thread
MIchaelMainer marked this conversation as resolved.
Resolved
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',
Expand All @@ -24,3 +27,31 @@
'self', 'raw', 'polling', 'custom_headers', 'operation_config', 'content_version', 'kwargs',
'client', 'no_wait'
]

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'
}
}
48 changes: 24 additions & 24 deletions msgraph/cli/core/installed_extensions.py
Original file line number Diff line number Diff line change
@@ -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 = [
Comment thread
MIchaelMainer marked this conversation as resolved.
Resolved
'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',
]
26 changes: 26 additions & 0 deletions msgraph/cli/core/profile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
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:
# 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 {}


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(error_msg) from ex
7 changes: 5 additions & 2 deletions msgraph/command_modules/authentication/_help.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 <enter client id> --tenant-id <enter tenant id>
"""

helps['logout'] = """
Expand Down
4 changes: 2 additions & 2 deletions msgraph/command_modules/authentication/custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@
authentication = Authentication()


def login(scopes):
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)
logged_in = authentication.login(scopes, client_id, tenant_id)

if not logged_in:
raise CLIError('Login failed')
Expand Down
32 changes: 32 additions & 0 deletions msgraph/command_modules/profile/__init__.py
Original file line number Diff line number Diff line change
@@ -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.command_modules.profile._exception_handler import profile_exception_handler
import msgraph.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.command_modules.profile.custom#{}',
exception_handler=profile_exception_handler)
with self.command_group('cloud', command_type) as group:
group.command('select', 'select_cloud')
group.command('add', 'add_cloud')
Comment thread
jobala marked this conversation as resolved.
Resolved
Comment thread
jobala marked this conversation as resolved.
Resolved
group.command('show-current', 'current_cloud')
group.command('update', 'update_cloud')
group.command('delete', 'delete_cloud')

return self.command_table


COMMAND_LOADER_CLS = ProfileCommandsLoader
96 changes: 96 additions & 0 deletions msgraph/command_modules/profile/_cloud_manager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# 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
from msgraph.cli.core.exceptions import CLIError


class CloudManager:
Comment thread
MIchaelMainer marked this conversation as resolved.
Resolved
'''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()

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, 'An error occured while creating the cloud.')

def get_current_cloud(self) -> dict:
return self.profile.get('cloud', None)

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,
error_msg=f'An error occured while updating the "{cloud_name}" cloud')

# No need to keep looking for the cloud
break

return updated

def delete_cloud(self, name: str):
result = []
current_cloud = self.profile.get('cloud', None)

# 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

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')

for cloud in self.profile['user_defined_clouds']:
if name not in cloud.keys():
Comment thread
MIchaelMainer marked this conversation as resolved.
Resolved
result.append(cloud)

self.profile['user_defined_clouds'] = result
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)
write_profile(
self.profile,
error_msg=
'An error occured while setting the selected cloud, the CLI will use the PUBLIC cloud')
11 changes: 11 additions & 0 deletions msgraph/command_modules/profile/_exception_handler.py
Original file line number Diff line number Diff line change
@@ -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)
Loading