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 |
| 28 | import logging |
| 29 | import socket |
| 30 | import sys |
| 31 | |
| 32 | from optparse import OptionParser |
Joe Gregorio | 06d852b | 2011-03-25 15:03:10 -0400 | [diff] [blame^] | 33 | from client import FlowExchangeError |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 34 | |
| 35 | try: |
| 36 | from urlparse import parse_qsl |
| 37 | except ImportError: |
| 38 | from cgi import parse_qsl |
| 39 | |
| 40 | |
| 41 | FLAGS = gflags.FLAGS |
| 42 | |
| 43 | gflags.DEFINE_boolean('auth_local_webserver', True, |
| 44 | ('Run a local web server to handle redirects during ' |
| 45 | 'OAuth authorization.')) |
| 46 | |
| 47 | gflags.DEFINE_string('auth_host_name', 'localhost', |
| 48 | ('Host name to use when running a local web server to ' |
| 49 | 'handle redirects during OAuth authorization.')) |
| 50 | |
| 51 | gflags.DEFINE_multi_int('auth_host_port', [8080, 8090], |
| 52 | ('Port to use when running a local web server to ' |
| 53 | 'handle redirects during OAuth authorization.')) |
| 54 | |
| 55 | |
| 56 | class ClientRedirectServer(BaseHTTPServer.HTTPServer): |
| 57 | """A server to handle OAuth 2.0 redirects back to localhost. |
| 58 | |
| 59 | Waits for a single request and parses the query parameters |
| 60 | into query_params and then stops serving. |
| 61 | """ |
| 62 | query_params = {} |
| 63 | |
| 64 | |
| 65 | class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler): |
| 66 | """A handler for OAuth 2.0 redirects back to localhost. |
| 67 | |
| 68 | Waits for a single request and parses the query parameters |
| 69 | into the servers query_params and then stops serving. |
| 70 | """ |
| 71 | |
| 72 | def do_GET(s): |
| 73 | """Handle a GET request |
| 74 | |
| 75 | Parses the query parameters and prints a message |
| 76 | if the flow has completed. Note that we can't detect |
| 77 | if an error occurred. |
| 78 | """ |
| 79 | s.send_response(200) |
| 80 | s.send_header("Content-type", "text/html") |
| 81 | s.end_headers() |
| 82 | query = s.path.split('?', 1)[-1] |
| 83 | query = dict(parse_qsl(query)) |
| 84 | s.server.query_params = query |
| 85 | s.wfile.write("<html><head><title>Authentication Status</title></head>") |
| 86 | s.wfile.write("<body><p>The authentication flow has completed.</p>") |
| 87 | s.wfile.write("</body></html>") |
| 88 | |
| 89 | def log_message(self, format, *args): |
| 90 | """Do not log messages to stdout while running as command line program.""" |
| 91 | pass |
| 92 | |
| 93 | |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 94 | def run(flow, storage): |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 95 | """Core code for a command-line application. |
Joe Gregorio | fffa7d7 | 2011-02-18 17:20:39 -0500 | [diff] [blame] | 96 | |
| 97 | Args: |
| 98 | flow: Flow, an OAuth 2.0 Flow to step through. |
| 99 | storage: Storage, a Storage to store the credential in. |
| 100 | |
| 101 | Returns: |
| 102 | Credentials, the obtained credential. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 103 | """ |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 104 | if FLAGS.auth_local_webserver: |
| 105 | success = False |
| 106 | port_number = 0 |
| 107 | for port in FLAGS.auth_host_port: |
| 108 | port_number = port |
| 109 | try: |
| 110 | httpd = BaseHTTPServer.HTTPServer((FLAGS.auth_host_name, port), |
| 111 | ClientRedirectHandler) |
| 112 | except socket.error, e: |
| 113 | pass |
| 114 | else: |
| 115 | success = True |
| 116 | break |
| 117 | FLAGS.auth_local_webserver = success |
| 118 | |
| 119 | if FLAGS.auth_local_webserver: |
| 120 | oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number) |
| 121 | else: |
| 122 | oauth_callback = 'oob' |
| 123 | authorize_url = flow.step1_get_authorize_url(oauth_callback) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 124 | |
| 125 | print 'Go to the following link in your browser:' |
| 126 | print authorize_url |
| 127 | print |
| 128 | |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 129 | if FLAGS.auth_local_webserver: |
| 130 | httpd.handle_request() |
| 131 | if 'error' in httpd.query_params: |
| 132 | sys.exit('Authentication request was rejected.') |
| 133 | if 'code' in httpd.query_params: |
| 134 | code = httpd.query_params['code'] |
| 135 | else: |
| 136 | accepted = 'n' |
| 137 | while accepted.lower() == 'n': |
| 138 | accepted = raw_input('Have you authorized me? (y/n) ') |
| 139 | code = raw_input('What is the verification code? ').strip() |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 140 | |
Joe Gregorio | fffa7d7 | 2011-02-18 17:20:39 -0500 | [diff] [blame] | 141 | try: |
| 142 | credentials = flow.step2_exchange(code) |
Joe Gregorio | 06d852b | 2011-03-25 15:03:10 -0400 | [diff] [blame^] | 143 | except FlowExchangeError: |
Joe Gregorio | fffa7d7 | 2011-02-18 17:20:39 -0500 | [diff] [blame] | 144 | sys.exit('The authentication has failed.') |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 145 | |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 146 | storage.put(credentials) |
| 147 | credentials.set_store(storage.put) |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 148 | print "You have successfully authenticated." |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 149 | |
| 150 | return credentials |