|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import contextvars |
| 3 | +import json |
| 4 | +import urllib.parse |
| 5 | +import webbrowser |
| 6 | +from pathlib import Path |
| 7 | +from wsgiref.simple_server import make_server |
| 8 | +from ..cli import scriptor_config |
| 9 | +import requests |
| 10 | + |
| 11 | +PORT = 60_000 |
| 12 | + |
| 13 | + |
| 14 | + |
| 15 | +def callback_app(environ: dict, start_response): |
| 16 | + qs = urllib.parse.parse_qs(environ["QUERY_STRING"]) |
| 17 | + callback_app.cookie.set(qs["cookie"][0]) |
| 18 | + callback_app.app.set(qs["app"][0]) |
| 19 | + start_response("200 OK", [('Content-Type', 'text/plain; charset=utf-8')]) |
| 20 | + return [b"This was successful. You can now close this site."] |
| 21 | + |
| 22 | + |
| 23 | +callback_app.cookie = contextvars.ContextVar("Cookie") |
| 24 | +callback_app.app = contextvars.ContextVar("App") |
| 25 | + |
| 26 | + |
| 27 | +def ensure_login( |
| 28 | + app: str, |
| 29 | + *, |
| 30 | + open_browser: bool = True, |
| 31 | + host: str = None, |
| 32 | +) -> bool: |
| 33 | + |
| 34 | + |
| 35 | + with make_server('', PORT, callback_app) as httpd: |
| 36 | + sa = httpd.socket.getsockname() |
| 37 | + print("Serving HTTP on", sa[0], "port", sa[1], "...") |
| 38 | + |
| 39 | + if host is None: |
| 40 | + host = f"https://{app}.appspot.com" |
| 41 | + url = f'{host}/vi/user/get_cookie_for_app?redirect_to=http://localhost:{PORT}' |
| 42 | + if open_browser: |
| 43 | + webbrowser.open(url) |
| 44 | + else: |
| 45 | + print("Open this URL in your browser:") |
| 46 | + print(url) |
| 47 | + |
| 48 | + httpd.handle_request() # serve one request, then exit |
| 49 | + |
| 50 | + cookie_str: str = callback_app.cookie.get() |
| 51 | + key, value = cookie_str.split(";", 1)[0].split("=") |
| 52 | + scriptor_config.get("cookies",{})[key] = value |
| 53 | + scriptor_config.save() |
| 54 | + |
| 55 | + return True |
| 56 | + |
| 57 | + |
| 58 | + |
| 59 | + |
0 commit comments