| 1 |
import asyncio |
| 2 |
import logging |
| 3 |
import socket |
| 4 |
import webbrowser |
| 5 |
from pathlib import Path |
| 6 |
from pprint import pprint |
| 7 |
from urllib.parse import parse_qs |
| 8 |
import json |
| 9 |
|
| 10 |
from httpx_oauth.oauth2 import OAuth2, OAuth2Token |
| 11 |
|
| 12 |
from aioimaplib import IMAP4_SSL |
| 13 |
|
| 14 |
CALLBACK_HTTP_PORT = 12345 |
| 15 |
|
| 16 |
# for office365 |
| 17 |
client = OAuth2( |
| 18 |
"<your-client-id>", |
| 19 |
"<your-client-secret>", |
| 20 |
"https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize", |
| 21 |
"https://login.microsoftonline.com/organizations/oauth2/v2.0/token", |
| 22 |
) |
| 23 |
|
| 24 |
SCOPES = [ |
| 25 |
"offline_access", |
| 26 |
"https://outlook.office.com/IMAP.AccessAsUser.All", |
| 27 |
] |
| 28 |
|
| 29 |
# for google`` |
| 30 |
# this is not tested yet. |
| 31 |
# from httpx_oauth.clients.google import GoogleOAuth2 |
| 32 |
|
| 33 |
# client = GoogleOAuth2( |
| 34 |
# "<your-client-id>", |
| 35 |
# "<your-client-secret>", |
| 36 |
# ) |
| 37 |
# SCOPES = ["https://mail.google.com/"] |
| 38 |
|
| 39 |
|
| 40 |
logging.basicConfig(level=logging.DEBUG) |
| 41 |
|
| 42 |
token_path = Path(__file__).parent / ".oauth_token.json" |
| 43 |
|
| 44 |
|
| 45 |
async def main(): |
| 46 |
|
| 47 |
token = await get_token() |
| 48 |
client = IMAP4_SSL("outlook.office365.com") |
| 49 |
|
| 50 |
await client.wait_hello_from_server() |
| 51 |
result = await client.xoauth2("<your-username>", token) |
| 52 |
pprint(result.lines) |
| 53 |
|
| 54 |
await client.select() |
| 55 |
result = await client.uid_search("1:*", charset="us-ascii") |
| 56 |
|
| 57 |
pprint(result.lines) |
| 58 |
|
| 59 |
await client.close() |
| 60 |
|
| 61 |
|
| 62 |
# These are functions to aquire a token and persist it/refresh it |
| 63 |
# if you have issues you can delete the token .oauth_token.json to re-aquire it |
| 64 |
|
| 65 |
|
| 66 |
async def get_token(): |
| 67 |
if not token_path.is_file(): |
| 68 |
token = await authorization() |
| 69 |
else: |
| 70 |
with token_path.open() as f_in: |
| 71 |
token_dict = json.load(f_in) |
| 72 |
token = OAuth2Token(token_dict) |
| 73 |
|
| 74 |
if token.is_expired(): |
| 75 |
token = client.refresh_token(token["refresh_token"]) |
| 76 |
|
| 77 |
# write token to file |
| 78 |
with token_path.open("w") as f_out: |
| 79 |
json.dump(token, f_out, indent=4) |
| 80 |
|
| 81 |
return token["access_token"] |
| 82 |
|
| 83 |
|
| 84 |
async def start_server_and_open_browser(url): |
| 85 |
|
| 86 |
response_queue = asyncio.Queue(1) |
| 87 |
|
| 88 |
# start callback webserver |
| 89 |
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 90 |
server.bind(("localhost", CALLBACK_HTTP_PORT)) |
| 91 |
server.listen() |
| 92 |
# this is set so we can restart the server quickly without getting |
| 93 |
# OSError: [Errno 48] Address already in use errors |
| 94 |
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 95 |
server.setblocking(False) |
| 96 |
|
| 97 |
server_task = asyncio.create_task(run_http_server(server, response_queue)) |
| 98 |
|
| 99 |
webbrowser.open(url) |
| 100 |
|
| 101 |
val = await response_queue.get() |
| 102 |
server.close() |
| 103 |
server_task.cancel() |
| 104 |
|
| 105 |
return val |
| 106 |
|
| 107 |
|
| 108 |
async def authorization(): |
| 109 |
"""Authorizes""" |
| 110 |
|
| 111 |
callback_url = f"http://localhost:{CALLBACK_HTTP_PORT}/" |
| 112 |
|
| 113 |
url = await client.get_authorization_url(callback_url, scope=SCOPES) |
| 114 |
token_response = await start_server_and_open_browser(url) |
| 115 |
access_token = await client.get_access_token(token_response["code"][0], callback_url) |
| 116 |
|
| 117 |
return access_token |
| 118 |
|
| 119 |
|
| 120 |
# this is a really small webserver to be able to receive the callback from oauth |
| 121 |
# heavlily inspired by https://github.com/jangia/http_server/blob/master/server.py |
| 122 |
|
| 123 |
CHUNK_LIMIT = 50 |
| 124 |
DEFAULT_RESPONSE = "HTTP/1.1 {status} {status_msg}\r\nContent-Type: text/html; charset=UTF-8\r\nContent-Encoding: UTF-8\r\nAccept-Ranges: bytes\r\nConnection: closed\r\n\r\n{html}" |
| 125 |
|
| 126 |
|
| 127 |
def parse_request(request_str): |
| 128 |
part_one, part_two = request_str.split("\r\n\r\n") |
| 129 |
http_lines = part_one.split("\r\n") |
| 130 |
method, url, _ = http_lines[0].split(" ") |
| 131 |
if method != "GET": |
| 132 |
status, status_msg = 405, "Not allowed" |
| 133 |
else: |
| 134 |
status, status_msg = 200, "OK" |
| 135 |
|
| 136 |
return status, status_msg, url |
| 137 |
|
| 138 |
|
| 139 |
async def build_response(request, response_queue): |
| 140 |
status, status_msg, url = parse_request(request) |
| 141 |
html = "" |
| 142 |
# if there is code in the response it is the one we want |
| 143 |
if "code" in url: |
| 144 |
query = parse_qs(url.split("?", 1)[1]) |
| 145 |
await response_queue.put(query) |
| 146 |
html = "Thank you, auth is handed back to the cli." |
| 147 |
else: |
| 148 |
status = 404 |
| 149 |
status_msg = "Not Found" |
| 150 |
response = DEFAULT_RESPONSE.format( |
| 151 |
status=status, status_msg=status_msg, html=html |
| 152 |
).encode("utf-8") |
| 153 |
|
| 154 |
return response |
| 155 |
|
| 156 |
|
| 157 |
async def read_request(client): |
| 158 |
request = "" |
| 159 |
while True: |
| 160 |
chunk = (await asyncio.get_event_loop().sock_recv(client, CHUNK_LIMIT)).decode( |
| 161 |
"utf8" |
| 162 |
) |
| 163 |
request += chunk |
| 164 |
if len(chunk) < CHUNK_LIMIT: |
| 165 |
break |
| 166 |
|
| 167 |
return request |
| 168 |
|
| 169 |
|
| 170 |
async def handle_client(client, response_queue): |
| 171 |
request = await read_request(client) |
| 172 |
response = await build_response(request, response_queue) |
| 173 |
await asyncio.get_event_loop().sock_sendall(client, response) |
| 174 |
client.close() |
| 175 |
|
| 176 |
|
| 177 |
async def run_http_server(selected_server, response_queue): |
| 178 |
while True: |
| 179 |
client, _ = await asyncio.get_event_loop().sock_accept(selected_server) |
| 180 |
asyncio.create_task(handle_client(client, response_queue)) |
| 181 |
|
| 182 |
|
| 183 |
if __name__ == "__main__": |
| 184 |
asyncio.run(main()) |