Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 1 | # Copyright (C) 2010 Google Inc. |
| 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 | |
| 15 | """Command-line tools for authenticating via OAuth 2.0 |
| 16 | |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 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 |
| 19 | the same directory. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 20 | """ |
| 21 | |
| 22 | __author__ = 'jcgregorio@google.com (Joe Gregorio)' |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 23 | __all__ = ['run'] |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 24 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 25 | |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 26 | import BaseHTTPServer |
| 27 | import gflags |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 28 | import socket |
| 29 | import sys |
Joe Gregorio | 2fdd295 | 2012-01-17 09:03:28 -0500 | [diff] [blame] | 30 | import webbrowser |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 31 | |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 32 | from oauth2client.client import FlowExchangeError |
| 33 | from oauth2client.client import OOB_CALLBACK_URN |
| 34 | from oauth2client import util |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 35 | |
| 36 | try: |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 37 | from urlparse import parse_qsl |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 38 | except ImportError: |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 39 | from cgi import parse_qsl |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 40 | |
| 41 | |
| 42 | FLAGS = gflags.FLAGS |
| 43 | |
| 44 | gflags.DEFINE_boolean('auth_local_webserver', True, |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 45 | ('Run a local web server to handle redirects during ' |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 46 | 'OAuth authorization.')) |
| 47 | |
| 48 | gflags.DEFINE_string('auth_host_name', 'localhost', |
| 49 | ('Host name to use when running a local web server to ' |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 50 | 'handle redirects during OAuth authorization.')) |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 51 | |
| 52 | gflags.DEFINE_multi_int('auth_host_port', [8080, 8090], |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 53 | ('Port to use when running a local web server to ' |
| 54 | 'handle redirects during OAuth authorization.')) |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 55 | |
| 56 | |
| 57 | class ClientRedirectServer(BaseHTTPServer.HTTPServer): |
| 58 | """A server to handle OAuth 2.0 redirects back to localhost. |
| 59 | |
| 60 | Waits for a single request and parses the query parameters |
| 61 | into query_params and then stops serving. |
| 62 | """ |
| 63 | query_params = {} |
| 64 | |
| 65 | |
| 66 | class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler): |
| 67 | """A handler for OAuth 2.0 redirects back to localhost. |
| 68 | |
| 69 | Waits for a single request and parses the query parameters |
| 70 | into the servers query_params and then stops serving. |
| 71 | """ |
| 72 | |
| 73 | def do_GET(s): |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 74 | """Handle a GET request. |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 75 | |
| 76 | Parses the query parameters and prints a message |
| 77 | if the flow has completed. Note that we can't detect |
| 78 | if an error occurred. |
| 79 | """ |
| 80 | s.send_response(200) |
| 81 | s.send_header("Content-type", "text/html") |
| 82 | s.end_headers() |
| 83 | query = s.path.split('?', 1)[-1] |
| 84 | query = dict(parse_qsl(query)) |
| 85 | s.server.query_params = query |
| 86 | s.wfile.write("<html><head><title>Authentication Status</title></head>") |
| 87 | s.wfile.write("<body><p>The authentication flow has completed.</p>") |
| 88 | s.wfile.write("</body></html>") |
| 89 | |
| 90 | def log_message(self, format, *args): |
| 91 | """Do not log messages to stdout while running as command line program.""" |
| 92 | pass |
| 93 | |
| 94 | |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 95 | @util.positional(2) |
Joe Gregorio | 8e000ed | 2012-02-07 15:41:44 -0500 | [diff] [blame] | 96 | def run(flow, storage, http=None): |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 97 | """Core code for a command-line application. |
Joe Gregorio | fffa7d7 | 2011-02-18 17:20:39 -0500 | [diff] [blame] | 98 | |
Joe Gregorio | d98b248 | 2012-10-24 08:49:12 -0400 | [diff] [blame^] | 99 | The run() function is called from your application and runs through all the |
| 100 | steps to obtain credentials. It takes a Flow argument and attempts to open an |
| 101 | authorization server page in the user's default web browser. The server asks |
| 102 | the user to grant your application access to the user's data. If the user |
| 103 | grants access, the run() function returns new credentials. The new credentials |
| 104 | are also stored in the Storage argument, which updates the file associated |
| 105 | with the Storage object. |
| 106 | |
| 107 | It presumes it is run from a command-line application and supports the |
| 108 | following flags: |
| 109 | |
| 110 | --[no]auth_local_webserver |
| 111 | |
| 112 | Run a local web server to handle redirects during OAuth authorization. |
| 113 | |
| 114 | --auth_host_name |
| 115 | |
| 116 | Host name to use when running a local web server to handle redirects |
| 117 | during OAuth authorization. |
| 118 | |
| 119 | --auth_host_port |
| 120 | |
| 121 | Port to use when running a local web server to handle redirects during |
| 122 | OAuth authorization. |
| 123 | |
| 124 | Since it uses flags make sure to initialize the gflags module before calling |
| 125 | run(). |
| 126 | |
Joe Gregorio | fffa7d7 | 2011-02-18 17:20:39 -0500 | [diff] [blame] | 127 | Args: |
| 128 | flow: Flow, an OAuth 2.0 Flow to step through. |
| 129 | storage: Storage, a Storage to store the credential in. |
Joe Gregorio | 8e000ed | 2012-02-07 15:41:44 -0500 | [diff] [blame] | 130 | http: An instance of httplib2.Http.request |
| 131 | or something that acts like it. |
Joe Gregorio | fffa7d7 | 2011-02-18 17:20:39 -0500 | [diff] [blame] | 132 | |
| 133 | Returns: |
| 134 | Credentials, the obtained credential. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 135 | """ |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 136 | if FLAGS.auth_local_webserver: |
| 137 | success = False |
| 138 | port_number = 0 |
| 139 | for port in FLAGS.auth_host_port: |
| 140 | port_number = port |
| 141 | try: |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 142 | httpd = ClientRedirectServer((FLAGS.auth_host_name, port), |
| 143 | ClientRedirectHandler) |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 144 | except socket.error, e: |
| 145 | pass |
| 146 | else: |
| 147 | success = True |
| 148 | break |
| 149 | FLAGS.auth_local_webserver = success |
Joe Gregorio | 01c86b1 | 2012-06-07 14:31:32 -0400 | [diff] [blame] | 150 | if not success: |
| 151 | print 'Failed to start a local webserver listening on either port 8080' |
| 152 | print 'or port 9090. Please check your firewall settings and locally' |
| 153 | print 'running programs that may be blocking or using those ports.' |
| 154 | print |
| 155 | print 'Falling back to --noauth_local_webserver and continuing with', |
| 156 | print 'authorization.' |
| 157 | print |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 158 | |
| 159 | if FLAGS.auth_local_webserver: |
| 160 | oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number) |
| 161 | else: |
Joe Gregorio | f2326c0 | 2012-02-09 12:18:44 -0500 | [diff] [blame] | 162 | oauth_callback = OOB_CALLBACK_URN |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 163 | flow.redirect_uri = oauth_callback |
| 164 | authorize_url = flow.step1_get_authorize_url() |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 165 | |
Joe Gregorio | 8097e2a | 2011-05-17 11:11:34 -0400 | [diff] [blame] | 166 | if FLAGS.auth_local_webserver: |
Joe Gregorio | 2fdd295 | 2012-01-17 09:03:28 -0500 | [diff] [blame] | 167 | webbrowser.open(authorize_url, new=1, autoraise=True) |
| 168 | print 'Your browser has been opened to visit:' |
| 169 | print |
| 170 | print ' ' + authorize_url |
| 171 | print |
Joe Gregorio | 8097e2a | 2011-05-17 11:11:34 -0400 | [diff] [blame] | 172 | print 'If your browser is on a different machine then exit and re-run this' |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 173 | print 'application with the command-line parameter ' |
Joe Gregorio | 2fdd295 | 2012-01-17 09:03:28 -0500 | [diff] [blame] | 174 | print |
| 175 | print ' --noauth_local_webserver' |
| 176 | print |
| 177 | else: |
| 178 | print 'Go to the following link in your browser:' |
| 179 | print |
| 180 | print ' ' + authorize_url |
Joe Gregorio | 8097e2a | 2011-05-17 11:11:34 -0400 | [diff] [blame] | 181 | print |
| 182 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 183 | code = None |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 184 | if FLAGS.auth_local_webserver: |
| 185 | httpd.handle_request() |
| 186 | if 'error' in httpd.query_params: |
| 187 | sys.exit('Authentication request was rejected.') |
| 188 | if 'code' in httpd.query_params: |
| 189 | code = httpd.query_params['code'] |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 190 | else: |
| 191 | print 'Failed to find "code" in the query parameters of the redirect.' |
| 192 | sys.exit('Try running with --noauth_local_webserver.') |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 193 | else: |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 194 | code = raw_input('Enter verification code: ').strip() |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 195 | |
Joe Gregorio | fffa7d7 | 2011-02-18 17:20:39 -0500 | [diff] [blame] | 196 | try: |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 197 | credential = flow.step2_exchange(code, http=http) |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 198 | except FlowExchangeError, e: |
| 199 | sys.exit('Authentication has failed: %s' % e) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 200 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 201 | storage.put(credential) |
| 202 | credential.set_store(storage) |
| 203 | print 'Authentication successful.' |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 204 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 205 | return credential |