Ejemplo n.º 1
0
def assign_site_access(site_url, roles=None, clear_existing=False):
    """
    :param str site_url: Site Url
    :param list[str] roles: The list of roles to add
    :param bool clear_existing: Clear existing permissions first
    """

    client = GraphClient(acquire_token_by_client_credentials)
    target_site = client.sites.get_by_url(site_url).get().execute_query()
    apps = client.applications.filter(
        f"appId eq '{test_client_credentials.clientId}'").get().execute_query(
        )
    if len(apps) == 0:
        sys.exit("App not found")

    if clear_existing:
        pcol = target_site.permissions.get().execute_query()
        for p in pcol:  # type: Permission
            p.delete_object()
        client.execute_query()

    if roles:
        identities = [{
            "application": {
                "id": apps[0].properties["appId"],
                "displayName": apps[0].properties["displayName"]
            }
        }]
        target_site.permissions.add(
            roles=roles, grantedToIdentities=identities).execute_query()
 def setUpClass(cls):
     super(TestPermissions, cls).setUpClass()
     client = GraphClient(acquire_token_by_client_credentials)
     folder_name = "New_" + uuid.uuid4().hex
     cls.target_drive_item = client.sites.root.drive.root.create_folder(
         folder_name).execute_query()
     cls.client = client
Ejemplo n.º 3
0
from examples import acquire_token_by_username_password
from office365.graph_client import GraphClient

client = GraphClient(acquire_token_by_username_password)

result = client.groups.get_all().execute_query()
print("Total groups count (before): {0}".format(len(result)))

groups = client.groups.get().top(2).execute_query()
for cur_grp in groups:
    cur_grp.delete_object()
client.execute_batch()

result = client.groups.get_all().execute_query()
print("Total groups count (after): {0}".format(len(result)))

    """

    :type remote_folder: office365.onedrive.driveItem.DriveItem
    :type local_path: str
    """
    drive_items = remote_folder.children.get().execute_query()
    for drive_item in drive_items:
        if not drive_item.file.is_server_object_null:  # is file?
            # download file content
            with open(os.path.join(local_path, drive_item.name),
                      'wb') as local_file:
                drive_item.download(local_file)
                client.execute_query()
            print("File '{0}' has been downloaded".format(local_file.name))


# --------------------------------------------------------------------------
# Example demonstrates how to export OneDrive files into local file system
# --------------------------------------------------------------------------

# connect
client = GraphClient(get_token)

# load drive properties
target_user_name = settings.get('test_accounts')[1]
drive = client.users[target_user_name].drive
# download files from OneDrive
with tempfile.TemporaryDirectory() as path:
    download_files(drive.root, path)
    print("Done")
from office365.graph_client import GraphClient
from settings import settings


def acquire_token():
    """
    Acquire token (MSAL)
    """
    authority_url = 'https://login.microsoftonline.com/{0}'.format(
        settings.get('tenant'))
    app = msal.ConfidentialClientApplication(
        authority=authority_url,
        client_id=settings.get('client_credentials').get('client_id'),
        client_credential=settings.get('client_credentials').get(
            'client_secret'))
    result = app.acquire_token_for_client(
        scopes=["https://graph.microsoft.com/.default"])
    return result


client = GraphClient(acquire_token)
user_name = settings.get('test_accounts')[1]
target_drive = client.users[user_name].drive

local_path = "../../tests/data/SharePoint User Guide.docx"
with open(local_path, 'rb') as f:
    file_content = f.read()
file_name = os.path.basename(local_path)
target_file = target_drive.root.upload(file_name, file_content).execute_query()
print(f"File {target_file.web_url} has been uploaded")
Ejemplo n.º 6
0
def get_token_for_user():
    """
    Acquire token via user credentials
    """
    authority_url = 'https://login.microsoftonline.com/{0}'.format(
        settings['tenant'])
    auth_ctx = adal.AuthenticationContext(authority_url)
    token = auth_ctx.acquire_token_with_username_password(
        'https://graph.microsoft.com',
        settings['user_credentials']['username'],
        settings['user_credentials']['password'],
        settings['client_credentials']['client_id'])
    return token


def enum_folders_and_files(root_folder):
    drive_items = root_folder.children
    client.load(drive_items)
    client.execute_query()
    for drive_item in drive_items:
        item_type = drive_item.folder.is_server_object_null and "file" or "folder"
        print("Type: {0} Name: {1}".format(item_type, drive_item.name))
        if not drive_item.folder.is_server_object_null and drive_item.folder.childCount > 0:
            enum_folders_and_files(drive_item)


client = GraphClient(get_token_for_user)
root = client.me.drive.root
enum_folders_and_files(root)
Ejemplo n.º 7
0
        'https://graph.microsoft.com',
        settings['user_credentials']['username'],
        settings['user_credentials']['password'],
        settings['client_credentials']['client_id'])
    return token


def create_group_for_team(groups, name):
    grp_properties = GroupProfile(name)
    grp_properties.securityEnabled = False
    grp_properties.mailEnabled = True
    grp_properties.groupTypes = ["Unified"]
    target_group = groups.add(grp_properties)
    return target_group


def print_failure(retry_number):
    print(f"{retry_number}: trying to create a team...")


client = GraphClient(acquire_token)

group_name = "Team_" + uuid.uuid4().hex
result = client.teams.create(group_name)
client.execute_query_retry(max_retry=5, failure_callback=print_failure)
print("Team has been provisioned")

channels = result.value.channels
client.load(channels)
client.execute_query()
Ejemplo n.º 8
0
import os

from office365.graph_client import GraphClient


def get_token(auth_ctx):
    token = auth_ctx.acquire_token_with_client_credentials(
        "https://graph.microsoft.com",
        client_id,
        client_secret)
    return token


tenant_name = "mediadev88.onmicrosoft.com"
client_id, client_secret = os.environ['Office365_Python_Sdk_ClientCredentials'].split(';')

client = GraphClient(tenant_name, get_token)
drives = client.drives
client.load(drives)
client.execute_query()
for drive in drives:
    print("Drive url: {0}".format(drive.web_url))
from office365.graph_client import GraphClient
from office365.sharepoint.client_context import ClientContext
from tests import test_site_url, test_client_credentials


def export_to_file(path, content):
    metadata_xml = minidom.parseString(content.decode("utf-8")).toprettyxml(indent="   ")
    with open(path, "w") as fh:
        fh.write(metadata_xml)


parser = ArgumentParser()
parser.add_argument("-e", "--endpoint", dest="endpoint",
                    help="Import metadata endpoint", default="sharepoint")
parser.add_argument("-p", "--path",
                    dest="path", default="./metadata/SharePoint.xml",
                    help="Import metadata endpoint")

args = parser.parse_args()

if args.endpoint == "sharepoint":
    print("Importing SharePoint model metadata...")
    ctx = ClientContext(test_site_url).with_credentials(test_client_credentials)
    result = ctx.get_metadata().execute_query()
    export_to_file(args.path, result.value)
elif args.endpoint == "microsoftgraph":
    print("Importing Microsoft Graph model metadata...")
    client = GraphClient(acquire_token_by_client_credentials)
    result = client.get_metadata().execute_query()
    export_to_file(args.path, result.value)
Ejemplo n.º 10
0
from examples import acquire_token_by_username_password
from office365.graph_client import GraphClient
from office365.outlook.mail.file_attachment import FileAttachment
from office365.outlook.mail.message import Message

# The example is adapted from https://docs.microsoft.com/en-us/graph/api/user-sendmail?view=graph-rest-1.0

client = GraphClient(acquire_token_by_username_password)

message = client.me.messages.new()  # type: Message
message.subject = "Meet for lunch?"
message.body = "The new cafeteria is open."
message.to_recipients = ["*****@*****.**"]
file_attachment = FileAttachment(client)
file_attachment.content_bytes = "SGVsbG8gV29ybGQh"
file_attachment.name = "attachment.txt"
file_attachment.content_type = "text/plain"
message.attachments = [file_attachment]

json = message.to_json(client.pending_request().json_format)
client.me.send_mail(message).execute_query()
Ejemplo n.º 11
0
from settings import settings

from office365.graph_client import GraphClient


def get_token_for_user(auth_ctx):
    """

    :type auth_ctx: adal.AuthenticationContext
    """
    token = auth_ctx.acquire_token_with_username_password(
        'https://graph.microsoft.com',
        settings['user_credentials']['username'],
        settings['user_credentials']['password'],
        settings['client_credentials']['client_id'])
    return token


client = GraphClient(settings['tenant'], get_token_for_user)

deleted_groups = client.directory.deletedGroups.get().execute_query()
# deleted_users = client.directory.deletedUsers.get().execute_query()
groups_count = len(deleted_groups)

for index, deleted_grp in enumerate(deleted_groups):
    print("({0} of {1}) Deleting {2} group ...".format(
        index + 1, groups_count, deleted_grp.properties['displayName']))
    deleted_grp.delete_object()
    client.execute_query()
    print("Group deleted.")
 def setUpClass(cls):
     ci_tenant_name = settings['tenant']
     cls.client = GraphClient(ci_tenant_name, get_token)
 def setUpClass(cls):
     super(TestTermStore, cls).setUpClass()
     client = GraphClient(acquire_token_by_client_credentials)
     cls.target_store = client.sites.get_by_url(
         test_root_site_url).term_store
from examples import acquire_token_client_credentials
from office365.graph_client import GraphClient
from tests import test_user_principal_name, test_user_principal_name_alt

client = GraphClient(acquire_token_client_credentials)
message_json = {
    "Message": {
        "Subject":
        "Meet for lunch?",
        "Body": {
            "ContentType": "Text",
            "Content": "The new cafeteria is open."
        },
        "ToRecipients": [{
            "EmailAddress": {
                "Address": test_user_principal_name_alt
            }
        }]
    },
    "SaveToSentItems": "false"
}

client.users[test_user_principal_name].send_mail(message_json)
client.execute_query()
from settings import settings

from office365.graph_client import GraphClient


def get_token_for_user():
    authority_url = 'https://login.microsoftonline.com/{0}'.format(
        settings['tenant'])
    auth_ctx = adal.AuthenticationContext(authority_url)
    token = auth_ctx.acquire_token_with_username_password(
        'https://graph.microsoft.com',
        settings['user_credentials']['username'],
        settings['user_credentials']['password'],
        settings['client_credentials']['client_id'])
    return token


client = GraphClient(get_token_for_user)

deleted_groups = client.directory.deletedGroups.get().execute_query()
# deleted_users = client.directory.deletedUsers.get().execute_query()
groups_count = len(deleted_groups)

for index, deleted_grp in enumerate(deleted_groups):
    print("({0} of {1}) Deleting {2} group ...".format(
        index + 1, groups_count, deleted_grp.properties['displayName']))
    deleted_grp.delete_object()
    client.execute_query()
    print("Group deleted.")
Ejemplo n.º 16
0
 def setUpClass(cls):
     cls.client = GraphClient(get_token)
Ejemplo n.º 17
0
def download_files(remote_folder, local_path):
    """

    :type remote_folder: office365.onedrive.driveItem.DriveItem
    :type local_path: str
    """
    drive_items = remote_folder.children.get().execute_query()
    for drive_item in drive_items:
        if not drive_item.file.is_server_object_null:  # is file?
            # download file content
            with open(os.path.join(local_path, drive_item.name),
                      'wb') as local_file:
                drive_item.download(local_file)
                client.execute_query()
            print("File '{0}' has been downloaded".format(local_file.name))


# --------------------------------------------------------------------------
# Example demonstrates how to export OneDrive files into local file system
# --------------------------------------------------------------------------

# connect
client = GraphClient(settings['tenant'], get_token)

# load drive properties
drive = client.users["*****@*****.**"].drive
# download files from OneDrive
with tempfile.TemporaryDirectory() as path:
    download_files(drive.root, path)
    print("Done")
        settings['user_credentials']['password'],
        settings['client_credentials']['client_id'])
    return token


def generate_user_profile():
    fake = Faker()

    user_json = {
        'givenName': fake.name(),
        'companyName': fake.company(),
        'businessPhones': [fake.phone_number()],
        'officeLocation': fake.street_address(),
        'city': fake.city(),
        'country': fake.country(),
        'principalName': "{0}@{1}".format(fake.user_name(),
                                          settings['tenant']),
        'password': "******".format(random_seed),
        'accountEnabled': True
    }
    return UserProfile(**user_json)


client = GraphClient(settings['tenant'], acquire_token)

for idx in range(0, 5):
    user_profile = generate_user_profile()
    user = client.users.add(user_profile).execute_query()
    print("{0} user has been created".format(
        user.properties['userPrincipalName']))
from office365.graph_client import GraphClient


def get_token():
    """Acquire token via client credential flow (ADAL Python library is utilized)"""
    authority_url = 'https://login.microsoftonline.com/{0}'.format(
        settings['tenant'])
    auth_ctx = adal.AuthenticationContext(authority_url)
    token = auth_ctx.acquire_token_with_client_credentials(
        "https://graph.microsoft.com",
        settings['client_credentials']['client_id'],
        settings['client_credentials']['client_secret'])
    return token


client = GraphClient(get_token)
message_json = {
    "Message": {
        "Subject":
        "Meet for lunch?",
        "Body": {
            "ContentType": "Text",
            "Content": "The new cafeteria is open."
        },
        "ToRecipients": [{
            "EmailAddress": {
                "Address": settings.get('test_accounts')[1]
            }
        }]
    },
    "SaveToSentItems": "false"
import uuid

from examples import acquire_token_client_credentials
from office365.graph_client import GraphClient


def print_failure(retry_number):
    print(f"{retry_number}: trying to create a team...")


client = GraphClient(acquire_token_client_credentials)
group_name = "Team_" + uuid.uuid4().hex
result = client.teams.create(group_name)
client.execute_query_retry(max_retry=5, failure_callback=print_failure)
print("Team has been provisioned")
Ejemplo n.º 21
0
import os
import tempfile

from examples import acquire_token_by_username_password
from office365.graph_client import GraphClient

client = GraphClient(acquire_token_by_username_password)
# 1. address file by path and get file metadata
file_item = client.me.drive.root.get_by_path("archive/Sample.rtf").get().execute_query()

# 2. download file content
with tempfile.TemporaryDirectory() as local_path:
    with open(os.path.join(local_path, file_item.name), 'wb') as local_file:
        file_item.download(local_file).execute_query()
    print("File '{0}' has been downloaded into {1}".format(file_item.name, local_file.name))
import msal

from settings import settings
from office365.graph_client import GraphClient


def acquire_token_msal():
    """
    Acquire token via MSAL

    """
    authority_url = 'https://login.microsoftonline.com/{0}'.format(settings['tenant'])
    app = msal.ConfidentialClientApplication(
        authority=authority_url,
        client_id=settings['client_credentials']['client_id'],
        client_credential=settings['client_credentials']['client_secret']
    )
    result = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
    return result


client = GraphClient(acquire_token_msal)
teams = client.teams.get_all().execute_query()
for team in teams:
    print(team.id)
 def setUpClass(cls):
     cls.client = GraphClient(acquire_token_by_username_password)

def get_token_for_user(auth_ctx):
    """
    Acquire token via user credentials

    :type auth_ctx: adal.AuthenticationContext
    """
    token = auth_ctx.acquire_token_with_username_password(
        'https://graph.microsoft.com',
        settings['user_credentials']['username'],
        settings['user_credentials']['password'],
        settings['client_credentials']['client_id'])
    return token


def enum_folders_and_files(root_folder):
    drive_items = root_folder.children
    client.load(drive_items)
    client.execute_query()
    for drive_item in drive_items:
        item_type = drive_item.folder.is_server_object_null and "file" or "folder"
        print("Type: {0} Name: {1}".format(item_type, drive_item.name))
        if not drive_item.folder.is_server_object_null and drive_item.folder.childCount > 0:
            enum_folders_and_files(drive_item)


client = GraphClient(settings['tenant'], get_token_for_user)
root = client.me.drive.root
enum_folders_and_files(root)
from examples import acquire_token_client_credentials
from office365.graph_client import GraphClient

client = GraphClient(acquire_token_client_credentials)

groups = client.groups.get().top(10).execute_query()
index = 0
groups_count = len(groups)
while len(groups) > 0:
    cur_grp = groups[0]
    print("({0} of {1}) Deleting {2} group ...".format(
        index + 1, groups_count, cur_grp.properties['displayName']))
    cur_grp.delete_object().execute_query()
    print("Group deleted.")
    index += 1

deleted_groups = client.directory.deletedGroups.get().execute_query()
groups_count = len(deleted_groups)
index = 0
while len(deleted_groups) > 0:
    cur_grp = deleted_groups[0]
    print("({0} of {1}) Deleting {2} group permanently ...".format(
        index + 1, groups_count, cur_grp.properties['displayName']))
    cur_grp.delete_object().execute_query()
    print("Group deleted.")
    index += 1
 def setUpClass(cls):
     cls.client = GraphClient(acquire_token_by_client_credentials)