| 1 |
""" |
| 2 |
Classes used by the LocalServerLoginFlowManager to automatically receive an |
| 3 |
auth code from a redirect after user authentication through a locally run web-server. |
| 4 |
|
| 5 |
These classes generally shouldn't need to be used directly. |
| 6 |
""" |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
import importlib.resources |
| 11 |
import os |
| 12 |
import queue |
| 13 |
import socket |
| 14 |
import sys |
| 15 |
import time |
| 16 |
import typing as t |
| 17 |
from datetime import timedelta |
| 18 |
from http.server import BaseHTTPRequestHandler, HTTPServer |
| 19 |
from string import Template |
| 20 |
from urllib.parse import parse_qsl, urlparse |
| 21 |
|
| 22 |
from . import html_files |
| 23 |
from .errors import LocalServerLoginError |
| 24 |
|
| 25 |
_IS_WINDOWS = os.name == "nt" |
| 26 |
|
| 27 |
DEFAULT_HTML_TEMPLATE = Template( |
| 28 |
importlib.resources.files(html_files) |
| 29 |
.joinpath("local_server_landing_page.html") |
| 30 |
.read_text() |
| 31 |
) |
| 32 |
|
| 33 |
|
| 34 |
class RedirectHandler(BaseHTTPRequestHandler): |
| 35 |
""" |
| 36 |
BaseHTTPRequestHandler to be used by RedirectHTTPServer. |
| 37 |
Displays the RedirectHTTPServer's html_template and parses auth_code out of |
| 38 |
the redirect url. |
| 39 |
""" |
| 40 |
|
| 41 |
server: RedirectHTTPServer |
| 42 |
|
| 43 |
def do_GET(self) -> None: |
| 44 |
self.send_response(200) |
| 45 |
self.send_header("Content-type", "text/html") |
| 46 |
self.end_headers() |
| 47 |
|
| 48 |
html_template = self.server.html_template |
| 49 |
query_params = dict(parse_qsl(urlparse(self.path).query)) |
| 50 |
code = query_params.get("code") |
| 51 |
if code: |
| 52 |
self.wfile.write( |
| 53 |
html_template.substitute( |
| 54 |
post_login_message="", login_result="Login successful" |
| 55 |
).encode("utf-8") |
| 56 |
) |
| 57 |
self.server.return_code(code) |
| 58 |
else: |
| 59 |
msg = query_params.get("error_description", query_params.get("error")) |
| 60 |
|
| 61 |
self.wfile.write( |
| 62 |
html_template.substitute( |
| 63 |
post_login_message=msg, login_result="Login failed" |
| 64 |
).encode("utf-8") |
| 65 |
) |
| 66 |
|
| 67 |
self.server.return_code(LocalServerLoginError(msg)) |
| 68 |
|
| 69 |
|
| 70 |
class RedirectHTTPServer(HTTPServer): |
| 71 |
""" |
| 72 |
An HTTPServer which accepts an HTML `Template` to be displayed to the user |
| 73 |
and uses a Queue to receive an auth_code from its RequestHandler. |
| 74 |
""" |
| 75 |
|
| 76 |
WAIT_TIMEOUT = timedelta(minutes=15) |
| 77 |
|
| 78 |
def __init__( |
| 79 |
self, |
| 80 |
server_address: tuple[str, int], |
| 81 |
handler_class: type[BaseHTTPRequestHandler], |
| 82 |
html_template: Template, |
| 83 |
) -> None: |
| 84 |
super().__init__(server_address, handler_class) |
| 85 |
|
| 86 |
self.html_template = html_template |
| 87 |
self._auth_code_queue: queue.Queue[str | BaseException] = queue.Queue() |
| 88 |
|
| 89 |
def handle_error( |
| 90 |
self, |
| 91 |
request: socket.socket | tuple[bytes, socket.socket], |
| 92 |
client_address: t.Any, |
| 93 |
) -> None: |
| 94 |
_, excval, _ = sys.exc_info() |
| 95 |
assert excval is not None |
| 96 |
self._auth_code_queue.put(excval) |
| 97 |
|
| 98 |
def return_code(self, code: str | BaseException) -> None: |
| 99 |
self._auth_code_queue.put_nowait(code) |
| 100 |
|
| 101 |
def wait_for_code(self) -> str | BaseException: |
| 102 |
# Windows needs special handling as blocking prevents ctrl-c interrupts |
| 103 |
if _IS_WINDOWS: |
| 104 |
deadline = time.time() + self.WAIT_TIMEOUT.total_seconds() |
| 105 |
while time.time() < deadline: |
| 106 |
try: |
| 107 |
return self._auth_code_queue.get() |
| 108 |
except queue.Empty: |
| 109 |
time.sleep(1) |
| 110 |
else: |
| 111 |
try: |
| 112 |
return self._auth_code_queue.get(block=True, timeout=3600) |
| 113 |
except queue.Empty: |
| 114 |
pass |
| 115 |
raise LocalServerLoginError("Login timed out. Please try again.") |