Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(59)

Side by Side Diff: appengine/chromium_build_logs/third_party/oauth2client/tools.py

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

Powered by Google App Engine
This is Rietveld 408576698