def first(): if os.path.isfile('o365_token.txt'): global authAccount token_backend = FileSystemTokenBackend(token_filename='o365_token.txt') authAccount = Account(credentials, tenant_id=tenantId, token_backend=token_backend)
def get_calendar_events(): credentials = (config.client_id, config.client_secret) # For AWS Lambda - copy token file to /tmp (only directory with write permissions) if not os.path.exists('/tmp/ms_token.txt'): copyfile('resources/ms_token.txt', '/tmp/ms_token.txt') print('resources/ms_token.txt copied to /tmp') # TODO - refactor due to deprecation # token_backend = FileSystemTokenBackend(token_path='/tmp', token_filename='ms_token.txt') token_backend = FileSystemTokenBackend(token_path='/tmp', token_filename='ms_token.txt') account = Account(credentials, token_backend=token_backend) # get calendar schedule = account.schedule() # cal = schedule.get_calendar(calendar_name='Calendar') cal = schedule.get_calendar(calendar_name='Calendário') now = dt.datetime.utcnow().isoformat() # query calendar and get events that are happening right now q = cal.new_query('start').less_equal(now) q.chain(ChainOperator.AND).on_attribute('end').greater_equal(now) events = cal.get_events(query=q) events_filtered = [] for event in events: events_filtered += filter_out_events(event) events_filtered = events_filtered[0] if events_filtered else events_filtered if not events_filtered: return get_calendar_events_cocus() else: return events_filtered # return only one
def function_microsoft(): try: scopes = [ 'https://graph.microsoft.com/MailboxSettings.Read', 'https://graph.microsoft.com/MailboxSettings.ReadWrite', 'https://graph.microsoft.com/User.Read' ] # you can use scope helpers here (see Permissions and Scopes section) token_backend = FileSystemTokenBackend(token_path='', token_filename='my_token.txt') #protocol = MSGraphProtocol(api_version='v1.0') account = Account(credentials, token_backend=token_backend) if not account.is_authenticated: account.authenticate(scopes=scopes) with open('my_token.txt', 'r') as myfile: data = myfile.read() obj = json.loads(data) access_token = obj['access_token'] headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer {0}'.format(access_token) } api_url = 'https://graph.microsoft.com/v1.0/me/mailboxSettings' response = requests.get(api_url, headers=headers) info = json.loads(response.content.decode('utf-8')) return (info['automaticRepliesSetting']) except: return {'reply': False}
def msauth_step_two_callback(self): person_id = self.o365_state_tracker[self.o365_auth_state] token_backend = FileSystemTokenBackend(token_path="token_backend", token_filename=person_id) credentials = ( self.o365_client_id, self.o365_client_token, ) account = Account(credentials, token_backend=token_backend, tenant_id=self.o365_tenant_id) # account = Account(credentials, tenant_id=self.o365_tenant_id) callback = self.teams_bot_url + "/msauth_step_two_callback" result = account.con.request_token(request.url, state=self.o365_auth_state, redirect_uri=callback) self.o365_state_tracker.pop(self.o365_auth_state) # if result is True, then authentication was succesful # and the auth token is stored in the token backend if result: return "Success!"
def __get_mail(self, monitoring: Monitoring): """ メールを取得する Params ------ monitoring: Monitoring 監視設定オブジェクト """ config = Config() run_time = RunTime(monitoring.search_word) # メールボックスへの接続 credentials = (config.client_id, config.client_secret) token_backend = \ FileSystemTokenBackend( token_path=config.token_path, token_filename=config.token_file ) account = Account(credentials, token_backend=token_backend) mailbox = account.mailbox() # 件名と時刻でメールを絞り込む query = mailbox.new_query() \ .on_attribute('subject') \ .contains(monitoring.search_word) \ .on_attribute('receivedDateTime') \ .greater_equal(run_time.read()) messages = mailbox.get_messages(query=query, download_attachments=True) return messages
def functionpost_microsoft(data): try: scopes = [ 'https://graph.microsoft.com/MailboxSettings.Read', 'https://graph.microsoft.com/MailboxSettings.ReadWrite', 'https://graph.microsoft.com/User.Read' ] # you can use scope helpers here (see Permissions and Scopes section) token_backend = FileSystemTokenBackend(token_path='', token_filename='my_token.txt') #protocol = MSGraphProtocol(api_version='v1.0') account = Account(credentials, token_backend=token_backend) if not account.is_authenticated: account.authenticate(scopes=scopes) with open('my_token.txt', 'r') as myfile: tok = myfile.read() obj = json.loads(tok) access_token = obj['access_token'] headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer {0}'.format(access_token) } api_url = 'https://graph.microsoft.com/v1.0/me/mailboxSettings' info = {"automaticRepliesSetting": data} print('info is:::::') print(info) response = requests.patch(api_url, headers=headers, json=info) if response.status_code >= 500: print('[!] [{0}] Server Error'.format(response.status_code)) elif response.status_code == 404: print('[!] [{0}] URL not found: [{1}]'.format( response.status_code, api_url)) elif response.status_code == 401: print('[!] [{0}] Authentication Failed'.format( response.status_code)) elif response.status_code >= 400: print('[!] [{0}] Bad Request'.format(response.status_code)) print(info) print(response.content) elif response.status_code >= 300: print('[!] [{0}] Unexpected redirect.'.format( response.status_code)) elif response.status_code == 200: posted_content = json.loads(response.content) return (posted_content) else: print('[?] Unexpected Error: [HTTP {0}]: Content: {1}'.format( response.status_code, response.content)) except: return {'reply': False}
def get_365_account(self): token_backend = FileSystemTokenBackend(token_path='.',token_filename='o365_token.txt') credentials = tuple() with open('credentials.json','r') as f: data = json.load(f) credentials = (data['appid'],data['secret']) protocal = MSGraphProtocol(api_version='beta') account = Account(credentials,token_backend = token_backend,protocol=protocal) return account
def getAccount(user_id): """Get account by user""" # prepare token backend for user token_backend = FileSystemTokenBackend(token_path=config.TOKEN_PATH, token_filename=user_id + '.token') # prepare MSGraphProtocol for user my_protocol = MSGraphProtocol(config.API_VERSION, user_id) # setup account definition for user return Account(credentials=(config.CLIENT_ID, config.CLIENT_SECRET), protocol=my_protocol, scopes=config.SCOPES, token_backend=token_backend)
def __init__( self, site: str = None, creds: tuple[str, str] = CREDS, scopes: list[str] = None, auth_flow_type: str = 'authorization' ): TOKEN = TOKEN_PATH / 'o365_token.txt' token_backend = None if TOKEN.exists(): logger.debug(f"Using token file {TOKEN}") token_backend = FileSystemTokenBackend(token_path=TOKEN_PATH) token_backend.load_token() token_backend.get_token() scopes = scopes or ['offline_access', 'Sites.Manage.All'] OPTIONS = { 'token_backend': token_backend } if token_backend is not None else { 'scopes': scopes, 'auth_flow_type': auth_flow_type } super().__init__(creds, **OPTIONS) if not self.is_authenticated: self.authenticate() self.drives = self.storage().get_drives() self.site = self.get_site(site) if site else None self.drive = self.site.get_default_document_library() if self.site else self.storage().get_default_drive() self.root_folder = self.drive.get_root_folder()
def _get_calendar(self, name=None): token_path = pathlib.Path() / 'mrd' token_filename = 'o365_token.txt' token_backend = FileSystemTokenBackend(token_path=token_path, token_filename=token_filename) account = Account(credentials=self._credentials, scopes=self._scopes, token_backend=token_backend) schedule = account.schedule() if name is not None: return schedule.get_calendar(calendar_name=name) return schedule.get_default_calendar()
def main(): """ 認証を行う """ config = Config() credentials = (config.client_id, config.client_secret) token_backend = \ FileSystemTokenBackend( token_path=config.token_path, token_filename=config.token_file ) account = Account(credentials, token_backend=token_backend) if account.authenticate(scopes=['basic', 'message_all']): print('Authenticated!')
def get_office365_account(): credentials = (config_secrets.get('office365', 'client_id'), config_secrets.get('office365', 'client_secret')) ensure_token_dir() token_backend = FileSystemTokenBackend(token_path=TOKEN_DIR, token_filename='token.txt') account = Account(credentials, main_resource=config_secrets.get('office365', 'username'), auth_flow_type='credentials', tenant_id=config_secrets.get('office365', 'tenant_id'), token_backend=token_backend) account.authenticate() return account
def init_o365(protocol: MSOffice365Protocol = MSOffice365Protocol(), credentials: Callable = o365_credentials, token_path: Path = O365_DEFAULT_TOKEN_PATH, scopes: List[str] = O365_DEFAULT_SCOPES): token_backend = FileSystemTokenBackend(token_path=token_path / O365_DEFAULT_TOKEN_FILE_NAME) account = Account(credentials(), protocol=protocol, token_backend=token_backend) if not account.is_authenticated and os.path.exists( os.path.join(token_path, O365_DEFAULT_TOKEN_FILE_NAME)): account.con.refresh_token() elif not account.is_authenticated: account.authenticate(scopes=scopes, grant_type='client_credentials') return account
def get_cal(tok_file): tok_be = FileSystemTokenBackend(token_filename=tok_file) print(acc.is_authenticated) sched = acc.schedule() calendar = sched.get_default_calendar() q = calendar.new_query('start').greater_equal(dt.datetime.today()) q.chain('and').on_attribute('end').less_equal(dt.datetime.today() + relativedelta(months=1)) events = calendar.get_events(query=q, include_recurring=True) evlist = [] for event in events: evlist.append(event) evlist.sort(key=lambda x: x.start) return evlist
def _authenticate(self): token_backend = FileSystemTokenBackend( token_path=os.path.dirname(os.path.realpath(__file__))) connection = Connection(config.credentials, scopes=['basic', 'Calendars.Read'], token_backend=token_backend) connection.refresh_token() account = Account(config.credentials, scopes=['basic', 'Calendars.Read'], token_backend=token_backend) if not account.is_authenticated: if account.authenticate(): print('Authenticated!') else: print('Authentication failed!') return self._schedule = account.schedule()
def get_account(tenant: str, client_id: str, client_secret: str, tenant_id: str, interactive: bool = False) -> Account: " Get O365 Account " credentials = (client_id, client_secret) token_backend = FileSystemTokenBackend( os.path.expanduser(os.environ.get(ENV_HOME) or HOME), token_filename=tenant_id + ".json", ) account = Account( credentials, auth_flow_type="authorization", tenant_id=tenant_id, token_backend=token_backend, ) if not account.is_authenticated: if account.con.auth_flow_type in ("authorization", "public") and not interactive: raise Exception("Please run 'spo configure' to authenticate") if account.authenticate(scopes=O365_SCOPES): print("Authenticated!") return account
def get_team(obj_name, credentials, host, site, token_filepath=None, io=None): """ Returns a Sharepoint site object :param str obj_name: a list name or a path to an excel file in sharepoint :param tuple credentials: a tuple with Office 365 client_id and client_secret :param str host: A sharepoint host like anatel365.sharepoint.com :param str site: a site's name or team's name :param str token_filepath: path where the Office 365 token is or will be stored. :param str io: path to where downloaded objects (list or excel file) will be stored. :return: a Sharepoint Site :rtype: Site """ # obter o caracter de split do filepath split_char, to_path, name = get_path_name(obj_name=obj_name, io=io) # separar o token_filename do token_path if not token_filepath: token_filename = 'o365token.txt' token_path = to_path + split_char else: token_filename = token_filepath.split(split_char)[-1] token_path = split_char.join( token_filepath.split(split_char)[:-1]) + split_char # Obter o token token_backend = FileSystemTokenBackend(token_path=token_path, token_filename=token_filename) # criar o objeto account account = Account(credentials, token_backend=token_backend) # scope para sharepoint scopes = ['basic'] + MSGraphProtocol().get_scopes_for( user_provided_scopes='sharepoint') # Autenticação if not isfile(token_path + token_filename): if not account.authenticate(scopes=scopes): raise Exception( 'Não foi possível autenticar com as credenciais e token informados' ) sharepoint = account.sharepoint() team = sharepoint.get_site(host, 'sites/' + site) return team
def authenticate_outlook(): # authenticate microsoft graph api credentials credentials = (config.outlook_client_id, config.outlook_client_secret) token_backend = FileSystemTokenBackend( token_path=config.outlook_token_path, token_filename=config.outlook_token_filename) account = Account(credentials, token_backend=token_backend) if not account.is_authenticated: # not authenticated, throw error account.authenticate(scopes=config.outlook_scopes) connection = Connection(credentials, token_backend=token_backend, scopes=config.outlook_scopes) connection.refresh_token() print("Authenticated Outlook.") return account
def __get_mailbox(self, monitoring: Monitoring): """ メールボックスを取得する """ config = Config() # メールボックスへの接続 credentials = (config.client_id, config.client_secret) token_backend = \ FileSystemTokenBackend( token_path=config.token_path, token_filename=config.token_file ) account = Account(credentials, token_backend=token_backend) mailbox = account.mailbox() for folder in monitoring.search_directory: mailbox = mailbox.get_folder(folder_name=folder) return mailbox
def send_o365(api_key, secret, from_email, to_email, email_body, subject): credentials = (api_key, secret) tokenFile = "o365_token.txt" if not os.path.exists(os.path.exists(os.path.join(Path(__file__).parent, tokenFile))): logging.critical("o365 emailer cannot find token file. Sending emails will fail.") token_backend = FileSystemTokenBackend(token_path=Path(__file__).parent, token_filename=tokenFile) account = Account(credentials, token_backend=token_backend, scopes=['message_send']) if not account.authenticate(): #if not account.is_authenticated(scopes=['message_send']): account.authenticate() logging.critical("o365 emailer is not authenticated. Requires manual investigation.") example_mailbox = account.mailbox(resource=from_email) m = example_mailbox.new_message() m.to.add(to_email) m.subject = subject m.body = email_body m.send()
def get_o365_mail(emailfrom, start_date, end_date): scopes = ['basic', 'mailbox'] token_backend = FileSystemTokenBackend(token_path='.', token_filename='o365_token.txt') account = Account( scopes=scopes, credentials=('8cccb04f-b409-4d04-888b-20321dcc14b7', secret_config.o365_secret), token_backend=token_backend ) if not account.is_authenticated: # will check if there is a token and has not expired # ask for a login # console based authentication See Authentication for other flows account.authenticate() if account.is_authenticated: account.connection.refresh_token() my_mailbox = account.mailbox() my_inbox = my_mailbox.inbox_folder() try: converted_start_date = datetime.strptime(start_date, '%Y-%m-%d') converted_end_date = datetime.strptime(end_date, '%Y-%m-%d') except Exception as e: print("Could not convert start_date or end_date into a datetime.datetime ") raise e inbox_query = my_mailbox.new_query().on_attribute("from").contains(emailfrom) inbox_query = inbox_query.chain("and").on_attribute("created_date_time").greater_equal(converted_start_date) inbox_query = inbox_query.chain("and").on_attribute("created_date_time").less_equal(converted_end_date) messages = list() for message in my_inbox.get_messages(download_attachments=True, query=inbox_query): messages.append(message) return messages print("hammertime")
def __init__(self, config: Dict): self.client_id = config['client-id'] self.secret_id = config['secret-id'] self.calendar_name = config['name'] self.token_file = config['token-file'] self.hours = config['hours'] credentials = (self.client_id, self.secret_id) protocol = MSGraphProtocol() scopes = [ 'User.Read', 'Calendars.Read', 'Calendars.Read.Shared', 'offline_access' ] self.account = Account( credentials, protocol=protocol, token_backend=FileSystemTokenBackend(token_path=self.token_file)) if not self.account.is_authenticated: if self.account.authenticate(scopes=scopes): print('Authenticated!') else: print("Failed to authenticate") else: print("Skipping authentication because token already exists")
def msauth_step_one(self): # Verify required parameters provided if None in ( self.o365_client_id, self.o365_client_token, self.o365_tenant_id, self.o365_scopes, ): raise ValueError( "MS Auth requires o365_client_id, o365_client_token, o365_tenant_id, o365_scopes" ) person_id = request.args["person_id"] token_backend = FileSystemTokenBackend(token_path="token_backend", token_filename=person_id) credentials = ( self.o365_client_id, self.o365_client_token, ) callback = self.teams_bot_url + "/msauth_step_two_callback" account = Account(credentials, token_backend=token_backend, tenant_id=self.o365_tenant_id) # account = Account(credentials, tenant_id=self.o365_tenant_id) url, self.o365_auth_state = account.con.get_authorization_url( requested_scopes=self.o365_scopes, redirect_uri=callback) self.o365_state_tracker[self.o365_auth_state] = person_id return redirect(url)
if not os.path.exists('auth'): print('auth directory does not exist. Creating...') os.makedirs('auth') c = json.loads(open('secret/secret.json').read()) parser = argparse.ArgumentParser( description= "Authenticate email via M365 OAuth2.0 authentication. By Drew Sidman <*****@*****.**>" ) #required arguments req = parser.add_argument_group('Required arguments') req.add_argument('-e', '--email', type=str, metavar='', required=True, help='Email address') args = parser.parse_args() credentials = (c['client_id'], c['client_secret']) token_backend = FileSystemTokenBackend(token_path='auth', token_filename=args.email) account = Account(credentials, token_backend=token_backend) if account.authenticate(scopes=['basic', 'message_all']): print('Authenticated!')
if item.is_file: download_file(item, current_path) def create_folder(item, current_path): folder = os.path.join(current_path, item.name) os.makedirs(folder, exist_ok=1) print(f"Dossier {item.name} créé avec succès !") return folder def download_file(item, path): item.download(to_path=path, chunk_size=None) print(f"Fichier {item.name} téléchargé avec succès !") protocol = MSGraphProtocol(api_version='beta') credentials = ('7b9c81d7-2c01-4d48-86fc-9a7cd9700b85', 'cBPj06Vjh_[HNkntI-e6pEf.h1JKn12H') token_backend = FileSystemTokenBackend(token_path='my_folder', token_filename='my_token.txt') account = Account(credentials, protocol=protocol, token_backend=token_backend) account.authenticate( scopes=['basic', 'message_all', 'onedrive_all', 'address_book_all']) storage = account.storage() my_drive = storage.get_default_drive() save_folder(my_drive)
CONFIGURATOR_DESCRIPTION = ( "To link your O365 account, click the link, login, and authorize:") CONFIGURATOR_LINK_NAME = "Link O365 account" CONFIGURATOR_SUBMIT_CAPTION = "I authorized successfully" DEFAULT_CACHE_PATH = ".O365-token-cache" DEFAULT_NAME = "Office 365 Calendar" DOMAIN = "office365calendar" ICON = "mdi:office" SCOPE = [ "offline_access", "User.Read", "Calendars.Read", "Calendars.Read.Shared" ] TOKEN_BACKEND = FileSystemTokenBackend(token_path=DEFAULT_CACHE_PATH, token_filename="o365.token") PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Required(CONF_CLIENT_ID): cv.string, vol.Required(CONF_CLIENT_SECRET): cv.string, }) def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Spotify platform.""" callback_url = f"{hass.config.api.base_url}{AUTH_CALLBACK_PATH}"
from O365 import Account, FileSystemTokenBackend, MSGraphProtocol import time import datetime import re CLIENT_ID = '85b6aa4d-103c-48f4-b0da-d766f18c7518' SECRET_ID = 'edBgd-L0FAMELEYuaZ:t8=S8F9DoJhK]' credentials = (CLIENT_ID, SECRET_ID) protocol = MSGraphProtocol(default_resource='*****@*****.**') token_backend = FileSystemTokenBackend(token_path='auth_token', token_filename='auth_token.txt') scopes = ['Calendars.Read.Shared','offline_access'] account = Account(credentials, protocol=protocol, token_backend=token_backend) account.authenticate(scopes=scopes) schedule = account.schedule() calendar = schedule.get_default_calendar() start_time = float(time.time()) end_time = float(time.time()) flag = 0 def parse_event_string(event): event_string = str(event) start_index = event_string.find('from:') + 6 end_index = event_string.find('to:') - 1 start_meeting_time = event_string[start_index:end_index]
config.read(str(path)) items = dict(config.items('RoomInformation')) CLIENT_ID = items['client_id'] CLIENT_SECRET = items['client_secret'] MAIL_ID = items['id'] print("Generate token for id", CLIENT_ID, "with secret", CLIENT_SECRET) scopes = [ 'offline_access', 'https://graph.microsoft.com/Calendars.ReadWrite.Shared' ] token_path = BASEDIR / "mrd" token_filename = "o365_token.txt" path = token_path / token_filename token_backend = FileSystemTokenBackend(token_path=token_path, token_filename=token_filename) account = Account((CLIENT_ID, CLIENT_SECRET), token_backend=token_backend) if not account.is_authenticated: print( "No valid token found. Starting authentication process for <%s> ..." % MAIL_ID) if account.authenticate( redirect_uri= 'https://login.microsoftonline.com/common/oauth2/nativeclient', scopes=scopes): print("Successfully stored token file at", path.absolute()) else: print("Failed to store token file") else:
This script must be run on its own, outside the Azure Function app and the environment before you deploy. After you've obtained an AppID and Secret from Azure's GRAPH API, plug them and your email address in. Run the script. It should create a file o365_token.txt in the same directory as this script This file will have the access token inside that your Azure Function app will need to authenticate with Graph and send emails. See the detailed o365 library help or further instructions in the readme. ''' from O365 import Account, FileSystemTokenBackend from pathlib import Path appID = "Your App ID from Azure" c_secret = "Your client secret from Azure" from_email = "*****@*****.**" to_email = "*****@*****.**" token_backend = FileSystemTokenBackend(token_path=Path(__file__).parent, token_filename='o365_token.txt') credentials = (appID, c_secret) account = Account(credentials, token_backend=token_backend) if not account.authenticate(): account.authenticate() print("o365 emailer is not authenticated. Requires manual investigation.") example_mailbox = account.mailbox(resource=from_email) m = example_mailbox.new_message() m.to.add(to_email) m.subject = "This is a test setup email" m.body = "This is the body of a test setup email" m.send()
def get_con_obj(): credentials = (conf['OFFICE_CLIENT_ID'], conf['OFFICE_CLIENT_SECRET']) scopes = Core.get_scopes() return Connection(credentials, scopes=scopes, token_backend=FileSystemTokenBackend(token_filename='o365_token.txt'))