OAuth 2.0 uses new endpoints. OAuth 2.0 moderator sample uses gflags. OAuth 2.0 tools.run adds a local web server to handle redirect_uri if possible.
diff --git a/apiclient/ext/authtools.py b/apiclient/ext/authtools.py
index c383811..41c0767 100644
--- a/apiclient/ext/authtools.py
+++ b/apiclient/ext/authtools.py
@@ -25,7 +25,6 @@
import BaseHTTPServer
import logging
-import pickle
import socket
import sys
diff --git a/apiclient/oauth.py b/apiclient/oauth.py
index b9fe7d3..618b29f 100644
--- a/apiclient/oauth.py
+++ b/apiclient/oauth.py
@@ -290,9 +290,12 @@
"""Exhanges an authorized request token
for OAuthCredentials.
- verifier - either the verifier token, or a dictionary
+ Args:
+ verifier: string, dict - either the verifier token, or a dictionary
of the query parameters to the callback, which contains
the oauth_verifier.
+ Returns:
+ The Credentials object.
"""
if not (isinstance(verifier, str) or isinstance(verifier, unicode)):
diff --git a/oauth2client/tools.py b/oauth2client/tools.py
index e244525..05e8b05 100644
--- a/oauth2client/tools.py
+++ b/oauth2client/tools.py
@@ -23,6 +23,74 @@
__all__ = ['run']
+import BaseHTTPServer
+import gflags
+import logging
+import socket
+import sys
+
+from optparse import OptionParser
+from apiclient.oauth import RequestError
+
+try:
+ from urlparse import parse_qsl
+except ImportError:
+ from cgi import parse_qsl
+
+
+FLAGS = gflags.FLAGS
+
+gflags.DEFINE_boolean('auth_local_webserver', True,
+ ('Run a local web server to handle redirects during '
+ 'OAuth authorization.'))
+
+gflags.DEFINE_string('auth_host_name', 'localhost',
+ ('Host name to use when running a local web server to '
+ 'handle redirects during OAuth authorization.'))
+
+gflags.DEFINE_multi_int('auth_host_port', [8080, 8090],
+ ('Port to use when running a local web server to '
+ 'handle redirects during OAuth authorization.'))
+
+
+class ClientRedirectServer(BaseHTTPServer.HTTPServer):
+ """A server to handle OAuth 2.0 redirects back to localhost.
+
+ Waits for a single request and parses the query parameters
+ into query_params and then stops serving.
+ """
+ query_params = {}
+
+
+class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler):
+ """A handler for OAuth 2.0 redirects back to localhost.
+
+ Waits for a single request and parses the query parameters
+ into the servers query_params and then stops serving.
+ """
+
+ def do_GET(s):
+ """Handle a GET request
+
+ Parses the query parameters and prints a message
+ if the flow has completed. Note that we can't detect
+ if an error occurred.
+ """
+ s.send_response(200)
+ s.send_header("Content-type", "text/html")
+ s.end_headers()
+ query = s.path.split('?', 1)[-1]
+ query = dict(parse_qsl(query))
+ s.server.query_params = query
+ s.wfile.write("<html><head><title>Authentication Status</title></head>")
+ s.wfile.write("<body><p>The authentication flow has completed.</p>")
+ s.wfile.write("</body></html>")
+
+ def log_message(self, format, *args):
+ """Do not log messages to stdout while running as command line program."""
+ pass
+
+
def run(flow, storage):
"""Core code for a command-line application.
@@ -32,20 +100,43 @@
Returns:
Credentials, the obtained credential.
-
- Exceptions:
- RequestError: if step2 of the flow fails.
"""
- authorize_url = flow.step1_get_authorize_url('http://localhost:8080/')
+ if FLAGS.auth_local_webserver:
+ success = False
+ port_number = 0
+ for port in FLAGS.auth_host_port:
+ port_number = port
+ try:
+ httpd = BaseHTTPServer.HTTPServer((FLAGS.auth_host_name, port),
+ ClientRedirectHandler)
+ except socket.error, e:
+ pass
+ else:
+ success = True
+ break
+ FLAGS.auth_local_webserver = success
+
+ if FLAGS.auth_local_webserver:
+ oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number)
+ else:
+ oauth_callback = 'oob'
+ authorize_url = flow.step1_get_authorize_url(oauth_callback)
print 'Go to the following link in your browser:'
print authorize_url
print
- accepted = 'n'
- while accepted.lower() == 'n':
- accepted = raw_input('Have you authorized me? (y/n) ')
- code = raw_input('What is the verification code? ').strip()
+ if FLAGS.auth_local_webserver:
+ httpd.handle_request()
+ if 'error' in httpd.query_params:
+ sys.exit('Authentication request was rejected.')
+ if 'code' in httpd.query_params:
+ code = httpd.query_params['code']
+ else:
+ accepted = 'n'
+ while accepted.lower() == 'n':
+ accepted = raw_input('Have you authorized me? (y/n) ')
+ code = raw_input('What is the verification code? ').strip()
try:
credentials = flow.step2_exchange(code)
@@ -54,7 +145,6 @@
storage.put(credentials)
credentials.set_store(storage.put)
-
- print 'You have successfully authenticated.'
+ print "You have successfully authenticated."
return credentials
diff --git a/samples/oauth2/moderator/moderator.py b/samples/oauth2/moderator/moderator.py
index d547d70..1578abd 100644
--- a/samples/oauth2/moderator/moderator.py
+++ b/samples/oauth2/moderator/moderator.py
@@ -3,26 +3,31 @@
#
# Copyright 2010 Google Inc. All Rights Reserved.
-"""Simple command-line example for Buzz.
+"""Simple command-line example for Moderator.
-Command-line application that retrieves the users
-latest content and then adds a new entry.
+Command-line application that exercises the Google Moderator API.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
+import gflags
import httplib2
+import sys
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run
-# Uncomment to get low level HTTP logging
-#httplib2.debuglevel = 4
+FLAGS = gflags.FLAGS
+def main(argv):
+ try:
+ argv = FLAGS(argv)
+ except gflags.FlagsError, e:
+ print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
+ sys.exit(1)
-def main():
storage = Storage('moderator.dat')
credentials = storage.get()
@@ -87,4 +92,4 @@
if __name__ == '__main__':
- main()
+ main(sys.argv)