Joe Gregorio | f78b4b5 | 2011-01-04 09:26:14 -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 1.0 |
| 16 | |
| 17 | Do the OAuth 1.0 Three Legged Dance for |
| 18 | a command line application. Stores the generated |
| 19 | credentials in a common file that is used by |
| 20 | other example apps in the same directory. |
| 21 | """ |
| 22 | |
| 23 | __author__ = 'jcgregorio@google.com (Joe Gregorio)' |
| 24 | __all__ = ["run"] |
| 25 | |
| 26 | import BaseHTTPServer |
| 27 | import logging |
Joe Gregorio | f78b4b5 | 2011-01-04 09:26:14 -0500 | [diff] [blame] | 28 | import socket |
| 29 | import sys |
| 30 | |
| 31 | from optparse import OptionParser |
| 32 | from apiclient.oauth import RequestError |
| 33 | |
| 34 | try: |
| 35 | from urlparse import parse_qsl |
| 36 | except ImportError: |
| 37 | from cgi import parse_qsl |
| 38 | |
| 39 | |
| 40 | class ClientRedirectServer(BaseHTTPServer.HTTPServer): |
| 41 | """A server to handle OAuth 1.0 redirects back to localhost. |
| 42 | |
| 43 | Waits for a single request and parses the query parameters |
| 44 | into query_params and then stops serving. |
| 45 | """ |
| 46 | query_params = {} |
| 47 | |
| 48 | |
| 49 | class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler): |
| 50 | """A handler for OAuth 2.0 redirects back to localhost. |
| 51 | |
| 52 | Waits for a single request and parses the query parameters |
| 53 | into the servers query_params and then stops serving. |
| 54 | """ |
| 55 | |
| 56 | def do_GET(s): |
| 57 | """Handle a GET request |
| 58 | |
| 59 | Parses the query parameters and prints a message |
| 60 | if the flow has completed. Note that we can't detect |
| 61 | if an error occurred. |
| 62 | """ |
| 63 | s.send_response(200) |
| 64 | s.send_header("Content-type", "text/html") |
| 65 | s.end_headers() |
| 66 | query = s.path.split('?', 1)[-1] |
| 67 | query = dict(parse_qsl(query)) |
| 68 | s.server.query_params = query |
| 69 | s.wfile.write("<html><head><title>Authentication Status</title></head>") |
| 70 | s.wfile.write("<body><p>The authentication flow has completed.</p>") |
| 71 | s.wfile.write("</body></html>") |
| 72 | |
| 73 | def log_message(self, format, *args): |
| 74 | """Do not log messages to stdout while running as command line program.""" |
| 75 | pass |
| 76 | |
| 77 | |
Joe Gregorio | fffa7d7 | 2011-02-18 17:20:39 -0500 | [diff] [blame] | 78 | def run(flow, storage): |
Joe Gregorio | f78b4b5 | 2011-01-04 09:26:14 -0500 | [diff] [blame] | 79 | """Core code for a command-line application. |
Joe Gregorio | fffa7d7 | 2011-02-18 17:20:39 -0500 | [diff] [blame] | 80 | |
| 81 | Args: |
| 82 | flow: Flow, an OAuth 1.0 Flow to step through. |
| 83 | storage: Storage, a Storage to store the credential in. |
| 84 | |
| 85 | Returns: |
| 86 | Credentials, the obtained credential. |
| 87 | |
| 88 | Exceptions: |
| 89 | RequestError: if step2 of the flow fails. |
| 90 | Args: |
Joe Gregorio | f78b4b5 | 2011-01-04 09:26:14 -0500 | [diff] [blame] | 91 | """ |
| 92 | parser = OptionParser() |
Joe Gregorio | f78b4b5 | 2011-01-04 09:26:14 -0500 | [diff] [blame] | 93 | parser.add_option("-p", "--no_local_web_server", dest="localhost", |
| 94 | action="store_false", |
| 95 | default=True, |
| 96 | help="Do not run a web server on localhost to handle redirect URIs") |
| 97 | parser.add_option("-w", "--local_web_server", dest="localhost", |
| 98 | action="store_true", |
| 99 | default=True, |
| 100 | help="Run a web server on localhost to handle redirect URIs") |
| 101 | |
| 102 | (options, args) = parser.parse_args() |
| 103 | |
| 104 | host_name = 'localhost' |
| 105 | port_numbers = [8080, 8090] |
| 106 | if options.localhost: |
| 107 | server_class = BaseHTTPServer.HTTPServer |
| 108 | try: |
| 109 | port_number = port_numbers[0] |
| 110 | httpd = server_class((host_name, port_number), ClientRedirectHandler) |
| 111 | except socket.error: |
| 112 | port_number = port_numbers[1] |
| 113 | try: |
| 114 | httpd = server_class((host_name, port_number), ClientRedirectHandler) |
| 115 | except socket.error: |
| 116 | options.localhost = False |
| 117 | |
| 118 | if options.localhost: |
| 119 | oauth_callback = 'http://%s:%s/' % (host_name, port_number) |
| 120 | else: |
| 121 | oauth_callback = 'oob' |
| 122 | authorize_url = flow.step1_get_authorize_url(oauth_callback) |
| 123 | |
| 124 | print 'Go to the following link in your browser:' |
| 125 | print authorize_url |
| 126 | print |
| 127 | |
| 128 | if options.localhost: |
| 129 | httpd.handle_request() |
| 130 | if 'error' in httpd.query_params: |
| 131 | sys.exit('Authentication request was rejected.') |
| 132 | if 'oauth_verifier' in httpd.query_params: |
| 133 | code = httpd.query_params['oauth_verifier'] |
| 134 | else: |
| 135 | accepted = 'n' |
| 136 | while accepted.lower() == 'n': |
| 137 | accepted = raw_input('Have you authorized me? (y/n) ') |
| 138 | code = raw_input('What is the verification code? ').strip() |
| 139 | |
| 140 | try: |
| 141 | credentials = flow.step2_exchange(code) |
| 142 | except RequestError: |
| 143 | sys.exit('The authentication has failed.') |
| 144 | |
Joe Gregorio | fffa7d7 | 2011-02-18 17:20:39 -0500 | [diff] [blame] | 145 | storage.put(credentials) |
| 146 | credentials.set_store(storage.put) |
Joe Gregorio | f78b4b5 | 2011-01-04 09:26:14 -0500 | [diff] [blame] | 147 | print "You have successfully authenticated." |
Joe Gregorio | d81ecb0 | 2011-02-15 17:46:47 -0500 | [diff] [blame] | 148 | |
| 149 | return credentials |