blob: 236c859cf730ecc8a4c2d78ac364e1b078cddbd7 [file] [log] [blame]
Joe Gregorio695fdc12011-01-16 16:46:55 -05001# 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 Gregorio7c22ab22011-02-16 15:32:39 -050017Do the OAuth 2.0 Web Server dance for a command line application. Stores the
18generated credentials in a common file that is used by other example apps in
19the same directory.
Joe Gregorio695fdc12011-01-16 16:46:55 -050020"""
21
22__author__ = 'jcgregorio@google.com (Joe Gregorio)'
Joe Gregorio7c22ab22011-02-16 15:32:39 -050023__all__ = ['run']
Joe Gregorio695fdc12011-01-16 16:46:55 -050024
Joe Gregorio695fdc12011-01-16 16:46:55 -050025
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -050026import BaseHTTPServer
27import gflags
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -050028import socket
29import sys
Joe Gregorio2fdd2952012-01-17 09:03:28 -050030import webbrowser
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -050031
Joe Gregorio06d852b2011-03-25 15:03:10 -040032from client import FlowExchangeError
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -050033
34try:
Joe Gregorio9da2ad82011-09-11 14:04:44 -040035 from urlparse import parse_qsl
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -050036except ImportError:
Joe Gregorio9da2ad82011-09-11 14:04:44 -040037 from cgi import parse_qsl
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -050038
39
40FLAGS = gflags.FLAGS
41
42gflags.DEFINE_boolean('auth_local_webserver', True,
Joe Gregorio9da2ad82011-09-11 14:04:44 -040043 ('Run a local web server to handle redirects during '
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -050044 'OAuth authorization.'))
45
46gflags.DEFINE_string('auth_host_name', 'localhost',
47 ('Host name to use when running a local web server to '
Joe Gregorio9da2ad82011-09-11 14:04:44 -040048 'handle redirects during OAuth authorization.'))
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -050049
50gflags.DEFINE_multi_int('auth_host_port', [8080, 8090],
Joe Gregorio9da2ad82011-09-11 14:04:44 -040051 ('Port to use when running a local web server to '
52 'handle redirects during OAuth authorization.'))
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -050053
54
55class ClientRedirectServer(BaseHTTPServer.HTTPServer):
56 """A server to handle OAuth 2.0 redirects back to localhost.
57
58 Waits for a single request and parses the query parameters
59 into query_params and then stops serving.
60 """
61 query_params = {}
62
63
64class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler):
65 """A handler for OAuth 2.0 redirects back to localhost.
66
67 Waits for a single request and parses the query parameters
68 into the servers query_params and then stops serving.
69 """
70
71 def do_GET(s):
Joe Gregorio9da2ad82011-09-11 14:04:44 -040072 """Handle a GET request.
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -050073
74 Parses the query parameters and prints a message
75 if the flow has completed. Note that we can't detect
76 if an error occurred.
77 """
78 s.send_response(200)
79 s.send_header("Content-type", "text/html")
80 s.end_headers()
81 query = s.path.split('?', 1)[-1]
82 query = dict(parse_qsl(query))
83 s.server.query_params = query
84 s.wfile.write("<html><head><title>Authentication Status</title></head>")
85 s.wfile.write("<body><p>The authentication flow has completed.</p>")
86 s.wfile.write("</body></html>")
87
88 def log_message(self, format, *args):
89 """Do not log messages to stdout while running as command line program."""
90 pass
91
92
Joe Gregorio8e000ed2012-02-07 15:41:44 -050093def run(flow, storage, http=None):
Joe Gregorio695fdc12011-01-16 16:46:55 -050094 """Core code for a command-line application.
Joe Gregoriofffa7d72011-02-18 17:20:39 -050095
96 Args:
97 flow: Flow, an OAuth 2.0 Flow to step through.
98 storage: Storage, a Storage to store the credential in.
Joe Gregorio8e000ed2012-02-07 15:41:44 -050099 http: An instance of httplib2.Http.request
100 or something that acts like it.
Joe Gregoriofffa7d72011-02-18 17:20:39 -0500101
102 Returns:
103 Credentials, the obtained credential.
Joe Gregorio695fdc12011-01-16 16:46:55 -0500104 """
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -0500105 if FLAGS.auth_local_webserver:
106 success = False
107 port_number = 0
108 for port in FLAGS.auth_host_port:
109 port_number = port
110 try:
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400111 httpd = ClientRedirectServer((FLAGS.auth_host_name, port),
112 ClientRedirectHandler)
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -0500113 except socket.error, e:
114 pass
115 else:
116 success = True
117 break
118 FLAGS.auth_local_webserver = success
119
120 if FLAGS.auth_local_webserver:
121 oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number)
122 else:
123 oauth_callback = 'oob'
124 authorize_url = flow.step1_get_authorize_url(oauth_callback)
Joe Gregorio695fdc12011-01-16 16:46:55 -0500125
Joe Gregorio8097e2a2011-05-17 11:11:34 -0400126 if FLAGS.auth_local_webserver:
Joe Gregorio2fdd2952012-01-17 09:03:28 -0500127 webbrowser.open(authorize_url, new=1, autoraise=True)
128 print 'Your browser has been opened to visit:'
129 print
130 print ' ' + authorize_url
131 print
Joe Gregorio8097e2a2011-05-17 11:11:34 -0400132 print 'If your browser is on a different machine then exit and re-run this'
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400133 print 'application with the command-line parameter '
Joe Gregorio2fdd2952012-01-17 09:03:28 -0500134 print
135 print ' --noauth_local_webserver'
136 print
137 else:
138 print 'Go to the following link in your browser:'
139 print
140 print ' ' + authorize_url
Joe Gregorio8097e2a2011-05-17 11:11:34 -0400141 print
142
Joe Gregorio562b7312011-09-15 09:06:38 -0400143 code = None
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -0500144 if FLAGS.auth_local_webserver:
145 httpd.handle_request()
146 if 'error' in httpd.query_params:
147 sys.exit('Authentication request was rejected.')
148 if 'code' in httpd.query_params:
149 code = httpd.query_params['code']
Joe Gregorio562b7312011-09-15 09:06:38 -0400150 else:
151 print 'Failed to find "code" in the query parameters of the redirect.'
152 sys.exit('Try running with --noauth_local_webserver.')
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -0500153 else:
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400154 code = raw_input('Enter verification code: ').strip()
Joe Gregorio695fdc12011-01-16 16:46:55 -0500155
Joe Gregoriofffa7d72011-02-18 17:20:39 -0500156 try:
Joe Gregorio8e000ed2012-02-07 15:41:44 -0500157 credential = flow.step2_exchange(code, http)
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400158 except FlowExchangeError, e:
159 sys.exit('Authentication has failed: %s' % e)
Joe Gregorio695fdc12011-01-16 16:46:55 -0500160
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400161 storage.put(credential)
162 credential.set_store(storage)
163 print 'Authentication successful.'
Joe Gregoriodeeb0202011-02-15 14:49:57 -0500164
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400165 return credential