blob: c383811f5d32ece3808831df7009e614e9dc971a [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
27import logging
28import pickle
29import 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
41class ClientRedirectServer(BaseHTTPServer.HTTPServer):
42 """A server to handle OAuth 1.0 redirects back to localhost.
43
44 Waits for a single request and parses the query parameters
45 into query_params and then stops serving.
46 """
47 query_params = {}
48
49
50class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler):
51 """A handler for OAuth 2.0 redirects back to localhost.
52
53 Waits for a single request and parses the query parameters
54 into the servers query_params and then stops serving.
55 """
56
57 def do_GET(s):
58 """Handle a GET request
59
60 Parses the query parameters and prints a message
61 if the flow has completed. Note that we can't detect
62 if an error occurred.
63 """
64 s.send_response(200)
65 s.send_header("Content-type", "text/html")
66 s.end_headers()
67 query = s.path.split('?', 1)[-1]
68 query = dict(parse_qsl(query))
69 s.server.query_params = query
70 s.wfile.write("<html><head><title>Authentication Status</title></head>")
71 s.wfile.write("<body><p>The authentication flow has completed.</p>")
72 s.wfile.write("</body></html>")
73
74 def log_message(self, format, *args):
75 """Do not log messages to stdout while running as command line program."""
76 pass
77
78
Joe Gregoriofffa7d72011-02-18 17:20:39 -050079def run(flow, storage):
Joe Gregoriof78b4b52011-01-04 09:26:14 -050080 """Core code for a command-line application.
Joe Gregoriofffa7d72011-02-18 17:20:39 -050081
82 Args:
83 flow: Flow, an OAuth 1.0 Flow to step through.
84 storage: Storage, a Storage to store the credential in.
85
86 Returns:
87 Credentials, the obtained credential.
88
89 Exceptions:
90 RequestError: if step2 of the flow fails.
91 Args:
Joe Gregoriof78b4b52011-01-04 09:26:14 -050092 """
93 parser = OptionParser()
Joe Gregoriof78b4b52011-01-04 09:26:14 -050094 parser.add_option("-p", "--no_local_web_server", dest="localhost",
95 action="store_false",
96 default=True,
97 help="Do not run a web server on localhost to handle redirect URIs")
98 parser.add_option("-w", "--local_web_server", dest="localhost",
99 action="store_true",
100 default=True,
101 help="Run a web server on localhost to handle redirect URIs")
102
103 (options, args) = parser.parse_args()
104
105 host_name = 'localhost'
106 port_numbers = [8080, 8090]
107 if options.localhost:
108 server_class = BaseHTTPServer.HTTPServer
109 try:
110 port_number = port_numbers[0]
111 httpd = server_class((host_name, port_number), ClientRedirectHandler)
112 except socket.error:
113 port_number = port_numbers[1]
114 try:
115 httpd = server_class((host_name, port_number), ClientRedirectHandler)
116 except socket.error:
117 options.localhost = False
118
119 if options.localhost:
120 oauth_callback = 'http://%s:%s/' % (host_name, port_number)
121 else:
122 oauth_callback = 'oob'
123 authorize_url = flow.step1_get_authorize_url(oauth_callback)
124
125 print 'Go to the following link in your browser:'
126 print authorize_url
127 print
128
129 if options.localhost:
130 httpd.handle_request()
131 if 'error' in httpd.query_params:
132 sys.exit('Authentication request was rejected.')
133 if 'oauth_verifier' in httpd.query_params:
134 code = httpd.query_params['oauth_verifier']
135 else:
136 accepted = 'n'
137 while accepted.lower() == 'n':
138 accepted = raw_input('Have you authorized me? (y/n) ')
139 code = raw_input('What is the verification code? ').strip()
140
141 try:
142 credentials = flow.step2_exchange(code)
143 except RequestError:
144 sys.exit('The authentication has failed.')
145
Joe Gregoriofffa7d72011-02-18 17:20:39 -0500146 storage.put(credentials)
147 credentials.set_store(storage.put)
Joe Gregoriof78b4b52011-01-04 09:26:14 -0500148 print "You have successfully authenticated."
Joe Gregoriod81ecb02011-02-15 17:46:47 -0500149
150 return credentials