| OLD | NEW |
| (Empty) |
| 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 gflags | |
| 28 import logging | |
| 29 import socket | |
| 30 import sys | |
| 31 | |
| 32 from optparse import OptionParser | |
| 33 from apiclient.oauth import RequestError | |
| 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 1.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 1.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 | |
| 94 def run(flow, storage): | |
| 95 """Core code for a command-line application. | |
| 96 | |
| 97 Args: | |
| 98 flow: Flow, an OAuth 1.0 Flow to step through. | |
| 99 storage: Storage, a Storage to store the credential in. | |
| 100 | |
| 101 Returns: | |
| 102 Credentials, the obtained credential. | |
| 103 | |
| 104 Exceptions: | |
| 105 RequestError: if step2 of the flow fails. | |
| 106 Args: | |
| 107 """ | |
| 108 | |
| 109 if FLAGS.auth_local_webserver: | |
| 110 success = False | |
| 111 port_number = 0 | |
| 112 for port in FLAGS.auth_host_port: | |
| 113 port_number = port | |
| 114 try: | |
| 115 httpd = BaseHTTPServer.HTTPServer((FLAGS.auth_host_name, port), | |
| 116 ClientRedirectHandler) | |
| 117 except socket.error, e: | |
| 118 pass | |
| 119 else: | |
| 120 success = True | |
| 121 break | |
| 122 FLAGS.auth_local_webserver = success | |
| 123 | |
| 124 if FLAGS.auth_local_webserver: | |
| 125 oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number) | |
| 126 else: | |
| 127 oauth_callback = 'oob' | |
| 128 authorize_url = flow.step1_get_authorize_url(oauth_callback) | |
| 129 | |
| 130 print 'Go to the following link in your browser:' | |
| 131 print authorize_url | |
| 132 print | |
| 133 if FLAGS.auth_local_webserver: | |
| 134 print 'If your browser is on a different machine then exit and re-run this' | |
| 135 print 'application with the command-line parameter --noauth_local_webserver.
' | |
| 136 print | |
| 137 | |
| 138 if FLAGS.auth_local_webserver: | |
| 139 httpd.handle_request() | |
| 140 if 'error' in httpd.query_params: | |
| 141 sys.exit('Authentication request was rejected.') | |
| 142 if 'oauth_verifier' in httpd.query_params: | |
| 143 code = httpd.query_params['oauth_verifier'] | |
| 144 else: | |
| 145 accepted = 'n' | |
| 146 while accepted.lower() == 'n': | |
| 147 accepted = raw_input('Have you authorized me? (y/n) ') | |
| 148 code = raw_input('What is the verification code? ').strip() | |
| 149 | |
| 150 try: | |
| 151 credentials = flow.step2_exchange(code) | |
| 152 except RequestError: | |
| 153 sys.exit('The authentication has failed.') | |
| 154 | |
| 155 storage.put(credentials) | |
| 156 credentials.set_store(storage.put) | |
| 157 print "You have successfully authenticated." | |
| 158 | |
| 159 return credentials | |
| OLD | NEW |