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

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

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

Powered by Google App Engine
This is Rietveld 408576698