def acquire(cls, auth_endpoint, redirect_port): """Usage: ac = AuthCodeReceiver.acquire('http://.../authorize', 8088)""" webbrowser.open("http://localhost:{p}?{q}".format( p=redirect_port, q=urlencode({ "text": """Open this link to acquire auth code. If you prefer, you may want to use incognito window.""", "link": auth_endpoint, }))) logging.warn( """Listening on http://localhost:{}, and a browser window is opened for you on THIS machine, and waiting for human interaction. This function call will hang until an auth code is received. """.format(redirect_port)) server = HTTPServer(("", int(redirect_port)), cls) server.authcode = None while not server.authcode: # https://docs.python.org/2/library/basehttpserver.html#more-examples server.handle_request() return server.authcode
def obtain_auth_code(listen_port, auth_uri=None): """This function will start a web server listening on http://localhost:port and then you need to open a browser on this device and visit your auth_uri. When interaction finishes, this function will return the auth code, and then shut down the local web server. :param listen_port: The local web server will listen at http://localhost:<listen_port> Unless the authorization server supports dynamic port, you need to use the same port when you register with your app. :param auth_uri: If provided, this function will try to open a local browser. :return: Hang indefinitely, until it receives and then return the auth code. """ exit_hint = "Visit http://localhost:{p}?code=exit to abort".format( p=listen_port) logger.warning(exit_hint) if auth_uri: page = "http://localhost:{p}?{q}".format( p=listen_port, q=urlencode({ "text": "Open this link to sign in. You may use incognito window", "link": auth_uri, "exit_hint": exit_hint, })) browse(page) server = HTTPServer(("", int(listen_port)), AuthCodeReceiver) try: server.authcode = None while not server.authcode: # Derived from # https://docs.python.org/2/library/basehttpserver.html#more-examples server.handle_request() return server.authcode finally: server.server_close()