1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 """Command-line tools for authenticating via OAuth 2.0
16
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.
20 """
21
22 __author__ = 'jcgregorio@google.com (Joe Gregorio)'
23 __all__ = ['run']
24
25
26 import BaseHTTPServer
27 import gflags
28 import socket
29 import sys
30 import webbrowser
31
32 from client import FlowExchangeError
33 from client import OOB_CALLBACK_URN
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
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
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
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
90 """Do not log messages to stdout while running as command line program."""
91 pass
92
93
94 -def run(flow, storage, http=None):
95 """Core code for a command-line application.
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 http: An instance of httplib2.Http.request
101 or something that acts like it.
102
103 Returns:
104 Credentials, the obtained credential.
105 """
106 if FLAGS.auth_local_webserver:
107 success = False
108 port_number = 0
109 for port in FLAGS.auth_host_port:
110 port_number = port
111 try:
112 httpd = ClientRedirectServer((FLAGS.auth_host_name, port),
113 ClientRedirectHandler)
114 except socket.error, e:
115 pass
116 else:
117 success = True
118 break
119 FLAGS.auth_local_webserver = success
120
121 if FLAGS.auth_local_webserver:
122 oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number)
123 else:
124 oauth_callback = OOB_CALLBACK_URN
125 authorize_url = flow.step1_get_authorize_url(oauth_callback)
126
127 if FLAGS.auth_local_webserver:
128 webbrowser.open(authorize_url, new=1, autoraise=True)
129 print 'Your browser has been opened to visit:'
130 print
131 print ' ' + authorize_url
132 print
133 print 'If your browser is on a different machine then exit and re-run this'
134 print 'application with the command-line parameter '
135 print
136 print ' --noauth_local_webserver'
137 print
138 else:
139 print 'Go to the following link in your browser:'
140 print
141 print ' ' + authorize_url
142 print
143
144 code = None
145 if FLAGS.auth_local_webserver:
146 httpd.handle_request()
147 if 'error' in httpd.query_params:
148 sys.exit('Authentication request was rejected.')
149 if 'code' in httpd.query_params:
150 code = httpd.query_params['code']
151 else:
152 print 'Failed to find "code" in the query parameters of the redirect.'
153 sys.exit('Try running with --noauth_local_webserver.')
154 else:
155 code = raw_input('Enter verification code: ').strip()
156
157 try:
158 credential = flow.step2_exchange(code, http)
159 except FlowExchangeError, e:
160 sys.exit('Authentication has failed: %s' % e)
161
162 storage.put(credential)
163 credential.set_store(storage)
164 print 'Authentication successful.'
165
166 return credential
167