blob: 5398bd859152d7c146f3bff9bc937ab19ce4099c [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
79def run(flow, filename):
80 """Core code for a command-line application.
81 """
82 parser = OptionParser()
83 parser.add_option("-f", "--file", dest="filename",
84 default=filename, help="write credentials to FILE", metavar="FILE")
85 parser.add_option("-p", "--no_local_web_server", dest="localhost",
86 action="store_false",
87 default=True,
88 help="Do not run a web server on localhost to handle redirect URIs")
89 parser.add_option("-w", "--local_web_server", dest="localhost",
90 action="store_true",
91 default=True,
92 help="Run a web server on localhost to handle redirect URIs")
93
94 (options, args) = parser.parse_args()
95
96 host_name = 'localhost'
97 port_numbers = [8080, 8090]
98 if options.localhost:
99 server_class = BaseHTTPServer.HTTPServer
100 try:
101 port_number = port_numbers[0]
102 httpd = server_class((host_name, port_number), ClientRedirectHandler)
103 except socket.error:
104 port_number = port_numbers[1]
105 try:
106 httpd = server_class((host_name, port_number), ClientRedirectHandler)
107 except socket.error:
108 options.localhost = False
109
110 if options.localhost:
111 oauth_callback = 'http://%s:%s/' % (host_name, port_number)
112 else:
113 oauth_callback = 'oob'
114 authorize_url = flow.step1_get_authorize_url(oauth_callback)
115
116 print 'Go to the following link in your browser:'
117 print authorize_url
118 print
119
120 if options.localhost:
121 httpd.handle_request()
122 if 'error' in httpd.query_params:
123 sys.exit('Authentication request was rejected.')
124 if 'oauth_verifier' in httpd.query_params:
125 code = httpd.query_params['oauth_verifier']
126 else:
127 accepted = 'n'
128 while accepted.lower() == 'n':
129 accepted = raw_input('Have you authorized me? (y/n) ')
130 code = raw_input('What is the verification code? ').strip()
131
132 try:
133 credentials = flow.step2_exchange(code)
134 except RequestError:
135 sys.exit('The authentication has failed.')
136
137 f = open(filename, 'w')
138 f.write(pickle.dumps(credentials))
139 f.close()
140 print "You have successfully authenticated."