tools.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. # Copyright 2014 Google Inc. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Command-line tools for authenticating via OAuth 2.0
  15. Do the OAuth 2.0 Web Server dance for a command line application. Stores the
  16. generated credentials in a common file that is used by other example apps in
  17. the same directory.
  18. """
  19. from __future__ import print_function
  20. import logging
  21. import socket
  22. import sys
  23. from six.moves import BaseHTTPServer
  24. from six.moves import http_client
  25. from six.moves import input
  26. from six.moves import urllib
  27. from oauth2client import _helpers
  28. from oauth2client import client
  29. __all__ = ['argparser', 'run_flow', 'message_if_missing']
  30. _CLIENT_SECRETS_MESSAGE = """WARNING: Please configure OAuth 2.0
  31. To make this sample run you will need to populate the client_secrets.json file
  32. found at:
  33. {file_path}
  34. with information from the APIs Console <https://code.google.com/apis/console>.
  35. """
  36. _FAILED_START_MESSAGE = """
  37. Failed to start a local webserver listening on either port 8080
  38. or port 8090. Please check your firewall settings and locally
  39. running programs that may be blocking or using those ports.
  40. Falling back to --noauth_local_webserver and continuing with
  41. authorization.
  42. """
  43. _BROWSER_OPENED_MESSAGE = """
  44. Your browser has been opened to visit:
  45. {address}
  46. If your browser is on a different machine then exit and re-run this
  47. application with the command-line parameter
  48. --noauth_local_webserver
  49. """
  50. _GO_TO_LINK_MESSAGE = """
  51. Go to the following link in your browser:
  52. {address}
  53. """
  54. def _CreateArgumentParser():
  55. try:
  56. import argparse
  57. except ImportError: # pragma: NO COVER
  58. return None
  59. parser = argparse.ArgumentParser(add_help=False)
  60. parser.add_argument('--auth_host_name', default='localhost',
  61. help='Hostname when running a local web server.')
  62. parser.add_argument('--noauth_local_webserver', action='store_true',
  63. default=False, help='Do not run a local web server.')
  64. parser.add_argument('--auth_host_port', default=[8080, 8090], type=int,
  65. nargs='*', help='Port web server should listen on.')
  66. parser.add_argument(
  67. '--logging_level', default='ERROR',
  68. choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
  69. help='Set the logging level of detail.')
  70. return parser
  71. # argparser is an ArgumentParser that contains command-line options expected
  72. # by tools.run(). Pass it in as part of the 'parents' argument to your own
  73. # ArgumentParser.
  74. argparser = _CreateArgumentParser()
  75. class ClientRedirectServer(BaseHTTPServer.HTTPServer):
  76. """A server to handle OAuth 2.0 redirects back to localhost.
  77. Waits for a single request and parses the query parameters
  78. into query_params and then stops serving.
  79. """
  80. query_params = {}
  81. class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  82. """A handler for OAuth 2.0 redirects back to localhost.
  83. Waits for a single request and parses the query parameters
  84. into the servers query_params and then stops serving.
  85. """
  86. def do_GET(self):
  87. """Handle a GET request.
  88. Parses the query parameters and prints a message
  89. if the flow has completed. Note that we can't detect
  90. if an error occurred.
  91. """
  92. self.send_response(http_client.OK)
  93. self.send_header('Content-type', 'text/html')
  94. self.end_headers()
  95. parts = urllib.parse.urlparse(self.path)
  96. query = _helpers.parse_unique_urlencoded(parts.query)
  97. self.server.query_params = query
  98. self.wfile.write(
  99. b'<html><head><title>Authentication Status</title></head>')
  100. self.wfile.write(
  101. b'<body><p>The authentication flow has completed.</p>')
  102. self.wfile.write(b'</body></html>')
  103. def log_message(self, format, *args):
  104. """Do not log messages to stdout while running as cmd. line program."""
  105. @_helpers.positional(3)
  106. def run_flow(flow, storage, flags=None, http=None):
  107. """Core code for a command-line application.
  108. The ``run()`` function is called from your application and runs
  109. through all the steps to obtain credentials. It takes a ``Flow``
  110. argument and attempts to open an authorization server page in the
  111. user's default web browser. The server asks the user to grant your
  112. application access to the user's data. If the user grants access,
  113. the ``run()`` function returns new credentials. The new credentials
  114. are also stored in the ``storage`` argument, which updates the file
  115. associated with the ``Storage`` object.
  116. It presumes it is run from a command-line application and supports the
  117. following flags:
  118. ``--auth_host_name`` (string, default: ``localhost``)
  119. Host name to use when running a local web server to handle
  120. redirects during OAuth authorization.
  121. ``--auth_host_port`` (integer, default: ``[8080, 8090]``)
  122. Port to use when running a local web server to handle redirects
  123. during OAuth authorization. Repeat this option to specify a list
  124. of values.
  125. ``--[no]auth_local_webserver`` (boolean, default: ``True``)
  126. Run a local web server to handle redirects during OAuth
  127. authorization.
  128. The tools module defines an ``ArgumentParser`` the already contains the
  129. flag definitions that ``run()`` requires. You can pass that
  130. ``ArgumentParser`` to your ``ArgumentParser`` constructor::
  131. parser = argparse.ArgumentParser(
  132. description=__doc__,
  133. formatter_class=argparse.RawDescriptionHelpFormatter,
  134. parents=[tools.argparser])
  135. flags = parser.parse_args(argv)
  136. Args:
  137. flow: Flow, an OAuth 2.0 Flow to step through.
  138. storage: Storage, a ``Storage`` to store the credential in.
  139. flags: ``argparse.Namespace``, (Optional) The command-line flags. This
  140. is the object returned from calling ``parse_args()`` on
  141. ``argparse.ArgumentParser`` as described above. Defaults
  142. to ``argparser.parse_args()``.
  143. http: An instance of ``httplib2.Http.request`` or something that
  144. acts like it.
  145. Returns:
  146. Credentials, the obtained credential.
  147. """
  148. if flags is None:
  149. flags = argparser.parse_args()
  150. logging.getLogger().setLevel(getattr(logging, flags.logging_level))
  151. if not flags.noauth_local_webserver:
  152. success = False
  153. port_number = 0
  154. for port in flags.auth_host_port:
  155. port_number = port
  156. try:
  157. httpd = ClientRedirectServer((flags.auth_host_name, port),
  158. ClientRedirectHandler)
  159. except socket.error:
  160. pass
  161. else:
  162. success = True
  163. break
  164. flags.noauth_local_webserver = not success
  165. if not success:
  166. print(_FAILED_START_MESSAGE)
  167. if not flags.noauth_local_webserver:
  168. oauth_callback = 'http://{host}:{port}/'.format(
  169. host=flags.auth_host_name, port=port_number)
  170. else:
  171. oauth_callback = client.OOB_CALLBACK_URN
  172. flow.redirect_uri = oauth_callback
  173. authorize_url = flow.step1_get_authorize_url()
  174. if not flags.noauth_local_webserver:
  175. import webbrowser
  176. webbrowser.open(authorize_url, new=1, autoraise=True)
  177. print(_BROWSER_OPENED_MESSAGE.format(address=authorize_url))
  178. else:
  179. print(_GO_TO_LINK_MESSAGE.format(address=authorize_url))
  180. code = None
  181. if not flags.noauth_local_webserver:
  182. httpd.handle_request()
  183. if 'error' in httpd.query_params:
  184. sys.exit('Authentication request was rejected.')
  185. if 'code' in httpd.query_params:
  186. code = httpd.query_params['code']
  187. else:
  188. print('Failed to find "code" in the query parameters '
  189. 'of the redirect.')
  190. sys.exit('Try running with --noauth_local_webserver.')
  191. else:
  192. code = input('Enter verification code: ').strip()
  193. try:
  194. credential = flow.step2_exchange(code, http=http)
  195. except client.FlowExchangeError as e:
  196. sys.exit('Authentication has failed: {0}'.format(e))
  197. storage.put(credential)
  198. credential.set_store(storage)
  199. print('Authentication successful.')
  200. return credential
  201. def message_if_missing(filename):
  202. """Helpful message to display if the CLIENT_SECRETS file is missing."""
  203. return _CLIENT_SECRETS_MESSAGE.format(file_path=filename)