blob: dc779b45748f041db9110475da02d7262be83555 [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
30
Joe Gregorio06d852b2011-03-25 15:03:10 -040031from client import FlowExchangeError
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -050032
33try:
Joe Gregorio9da2ad82011-09-11 14:04:44 -040034 from urlparse import parse_qsl
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -050035except ImportError:
Joe Gregorio9da2ad82011-09-11 14:04:44 -040036 from cgi import parse_qsl
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -050037
38
39FLAGS = gflags.FLAGS
40
41gflags.DEFINE_boolean('auth_local_webserver', True,
Joe Gregorio9da2ad82011-09-11 14:04:44 -040042 ('Run a local web server to handle redirects during '
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -050043 'OAuth authorization.'))
44
45gflags.DEFINE_string('auth_host_name', 'localhost',
46 ('Host name to use when running a local web server to '
Joe Gregorio9da2ad82011-09-11 14:04:44 -040047 'handle redirects during OAuth authorization.'))
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -050048
49gflags.DEFINE_multi_int('auth_host_port', [8080, 8090],
Joe Gregorio9da2ad82011-09-11 14:04:44 -040050 ('Port to use when running a local web server to '
51 'handle redirects during OAuth authorization.'))
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -050052
53
54class ClientRedirectServer(BaseHTTPServer.HTTPServer):
55 """A server to handle OAuth 2.0 redirects back to localhost.
56
57 Waits for a single request and parses the query parameters
58 into query_params and then stops serving.
59 """
60 query_params = {}
61
62
63class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler):
64 """A handler for OAuth 2.0 redirects back to localhost.
65
66 Waits for a single request and parses the query parameters
67 into the servers query_params and then stops serving.
68 """
69
70 def do_GET(s):
Joe Gregorio9da2ad82011-09-11 14:04:44 -040071 """Handle a GET request.
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -050072
73 Parses the query parameters and prints a message
74 if the flow has completed. Note that we can't detect
75 if an error occurred.
76 """
77 s.send_response(200)
78 s.send_header("Content-type", "text/html")
79 s.end_headers()
80 query = s.path.split('?', 1)[-1]
81 query = dict(parse_qsl(query))
82 s.server.query_params = query
83 s.wfile.write("<html><head><title>Authentication Status</title></head>")
84 s.wfile.write("<body><p>The authentication flow has completed.</p>")
85 s.wfile.write("</body></html>")
86
87 def log_message(self, format, *args):
88 """Do not log messages to stdout while running as command line program."""
89 pass
90
91
Joe Gregoriodeeb0202011-02-15 14:49:57 -050092def run(flow, storage):
Joe Gregorio695fdc12011-01-16 16:46:55 -050093 """Core code for a command-line application.
Joe Gregoriofffa7d72011-02-18 17:20:39 -050094
95 Args:
96 flow: Flow, an OAuth 2.0 Flow to step through.
97 storage: Storage, a Storage to store the credential in.
98
99 Returns:
100 Credentials, the obtained credential.
Joe Gregorio695fdc12011-01-16 16:46:55 -0500101 """
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -0500102 if FLAGS.auth_local_webserver:
103 success = False
104 port_number = 0
105 for port in FLAGS.auth_host_port:
106 port_number = port
107 try:
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400108 httpd = ClientRedirectServer((FLAGS.auth_host_name, port),
109 ClientRedirectHandler)
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -0500110 except socket.error, e:
111 pass
112 else:
113 success = True
114 break
115 FLAGS.auth_local_webserver = success
116
117 if FLAGS.auth_local_webserver:
118 oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number)
119 else:
120 oauth_callback = 'oob'
121 authorize_url = flow.step1_get_authorize_url(oauth_callback)
Joe Gregorio695fdc12011-01-16 16:46:55 -0500122
123 print 'Go to the following link in your browser:'
124 print authorize_url
125 print
Joe Gregorio8097e2a2011-05-17 11:11:34 -0400126 if FLAGS.auth_local_webserver:
127 print 'If your browser is on a different machine then exit and re-run this'
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400128 print 'application with the command-line parameter '
129 print '--noauth_local_webserver.'
Joe Gregorio8097e2a2011-05-17 11:11:34 -0400130 print
131
Joe Gregorio9e5fe4d2011-03-10 09:33:47 -0500132 if FLAGS.auth_local_webserver:
133 httpd.handle_request()
134 if 'error' in httpd.query_params:
135 sys.exit('Authentication request was rejected.')
136 if 'code' in httpd.query_params:
137 code = httpd.query_params['code']
138 else:
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400139 code = raw_input('Enter verification code: ').strip()
Joe Gregorio695fdc12011-01-16 16:46:55 -0500140
Joe Gregoriofffa7d72011-02-18 17:20:39 -0500141 try:
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400142 credential = flow.step2_exchange(code)
143 except FlowExchangeError, e:
144 sys.exit('Authentication has failed: %s' % e)
Joe Gregorio695fdc12011-01-16 16:46:55 -0500145
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400146 storage.put(credential)
147 credential.set_store(storage)
148 print 'Authentication successful.'
Joe Gregoriodeeb0202011-02-15 14:49:57 -0500149
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400150 return credential