blob: b1183abc574fcd4fce3fba008259fcf993706af1 [file] [log] [blame]
Joe Gregoriof78b4b52011-01-04 09:26:14 -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 1.0
16
17Do the OAuth 1.0 Three Legged Dance for
18a command line application. Stores the generated
19credentials in a common file that is used by
20other example apps in the same directory.
21"""
22
23__author__ = 'jcgregorio@google.com (Joe Gregorio)'
24__all__ = ["run"]
25
26import BaseHTTPServer
Joe Gregorio3b020d62011-05-27 14:04:59 -040027import gflags
Joe Gregoriof78b4b52011-01-04 09:26:14 -050028import logging
Joe Gregoriof78b4b52011-01-04 09:26:14 -050029import socket
30import sys
31
32from optparse import OptionParser
33from apiclient.oauth import RequestError
34
35try:
36 from urlparse import parse_qsl
37except ImportError:
38 from cgi import parse_qsl
39
40
Joe Gregorio3b020d62011-05-27 14:04:59 -040041FLAGS = gflags.FLAGS
42
43gflags.DEFINE_boolean('auth_local_webserver', True,
44 ('Run a local web server to handle redirects during '
45 'OAuth authorization.'))
46
47gflags.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
51gflags.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
Joe Gregoriof78b4b52011-01-04 09:26:14 -050056class 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
65class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler):
Joe Gregorio3b020d62011-05-27 14:04:59 -040066 """A handler for OAuth 1.0 redirects back to localhost.
Joe Gregoriof78b4b52011-01-04 09:26:14 -050067
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 Gregoriofffa7d72011-02-18 17:20:39 -050094def run(flow, storage):
Joe Gregoriof78b4b52011-01-04 09:26:14 -050095 """Core code for a command-line application.
Joe Gregoriofffa7d72011-02-18 17:20:39 -050096
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:
Joe Gregoriof78b4b52011-01-04 09:26:14 -0500107 """
Joe Gregoriof78b4b52011-01-04 09:26:14 -0500108
Joe Gregorio3b020d62011-05-27 14:04:59 -0400109 if FLAGS.auth_local_webserver:
110 success = False
111 port_number = 0
112 for port in FLAGS.auth_host_port:
113 port_number = port
Joe Gregoriof78b4b52011-01-04 09:26:14 -0500114 try:
Joe Gregorio3b020d62011-05-27 14:04:59 -0400115 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
Joe Gregoriof78b4b52011-01-04 09:26:14 -0500123
Joe Gregorio3b020d62011-05-27 14:04:59 -0400124 if FLAGS.auth_local_webserver:
125 oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number)
Joe Gregoriof78b4b52011-01-04 09:26:14 -0500126 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
Joe Gregorio3b020d62011-05-27 14:04:59 -0400133 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
Joe Gregoriof78b4b52011-01-04 09:26:14 -0500137
Joe Gregorio3b020d62011-05-27 14:04:59 -0400138 if FLAGS.auth_local_webserver:
Joe Gregoriof78b4b52011-01-04 09:26:14 -0500139 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
Joe Gregoriofffa7d72011-02-18 17:20:39 -0500155 storage.put(credentials)
156 credentials.set_store(storage.put)
Joe Gregoriof78b4b52011-01-04 09:26:14 -0500157 print "You have successfully authenticated."
Joe Gregoriod81ecb02011-02-15 17:46:47 -0500158
159 return credentials