diff --git a/.gitignore b/.gitignore index 5016749..4a503d8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ __pycache__ -refresh_token \ No newline at end of file +refresh_token +imap_smtp_refresh_token +imap_smtp_access_token diff --git a/get_token.py b/get_token.py index 38e7136..3aa27ca 100644 --- a/get_token.py +++ b/get_token.py @@ -1,8 +1,13 @@ from msal import ConfidentialClientApplication, SerializableTokenCache import config +import http.server import sys +import threading +import urllib.parse +import webbrowser -redirect_uri = "http://localhost" + +redirect_uri = "http://localhost:8745/" # We use the cache to extract the refresh token cache = SerializableTokenCache() @@ -10,16 +15,44 @@ app = ConfidentialClientApplication(config.ClientId, client_credential=config.Cl url = app.get_authorization_request_url(config.Scopes, redirect_uri=redirect_uri) -print('Navigate to the following url in a web browser:') -print(url) +try: + webbrowser.open(url) +except Exception: + print('Navigate to the following url in a web browser:') + print(url) -print() -print('After login, you will be redirected to a blank (or error) page with a url containing an access code. Paste the url below.') -resp = input('Response url: ') +class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + parsed_url = urllib.parse.urlparse(self.path) + parsed_query = urllib.parse.parse_qs(parsed_url.query) + global code + code = next(iter(parsed_query['code']), '') -i = resp.find('code') + 5 -code = resp[i : resp.find('&', i)] if i > 4 else resp + response_body = b'Success. Look back at your terminal.\r\n' + self.send_response(200) + self.send_header('Content-Type', 'text/plain') + self.send_header('Content-Length', len(response_body)) + self.end_headers() + self.wfile.write(response_body) + + global httpd + t = threading.Thread(target=lambda: httpd.shutdown()) + t.start() + + +code = '' + +server_address = ('', 8745) +httpd = http.server.HTTPServer(server_address, Handler) +httpd.serve_forever() + +if code == '': + print('After login, you will be redirected to a blank (or error) page with a url containing an access code. Paste the url below.') + resp = input('Response url: ') + + i = resp.find('code') + 5 + code = resp[i : resp.find('&', i)] if i > 4 else resp token = app.acquire_token_by_authorization_code(code, config.Scopes, redirect_uri=redirect_uri) diff --git a/refresh_token.py b/refresh_token.py index cd2577a..646ba9f 100644 --- a/refresh_token.py +++ b/refresh_token.py @@ -2,7 +2,6 @@ from msal import ConfidentialClientApplication, SerializableTokenCache import config import sys -redirect_uri = "http://localhost" print_access_token = True # We use the cache to extract the refresh token diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..ce88fed --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +msal