old_run.py 5.42 KB
Newer Older
1
# Copyright (C) 2013 Google Inc.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""This module holds the old run() function which is deprecated, the
tools.run_flow() function should be used in its place."""


import logging
import socket
import sys
import webbrowser

import gflags
25 26 27

from oauth2client import client
from oauth2client import util
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
from tools import ClientRedirectHandler
from tools import ClientRedirectServer


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.'))


@util.positional(2)
def run(flow, storage, http=None):
  """Core code for a command-line application.

51 52 53 54 55 56 57
  The run() function is called from your application and runs through all
  the steps to obtain credentials. It takes a Flow argument and attempts to
  open an authorization server page in the user's default web browser. The
  server asks the user to grant your application access to the user's data.
  If the user grants access, the run() function returns new credentials. The
  new credentials are also stored in the Storage argument, which updates the
  file associated with the Storage object.
58 59 60 61

  It presumes it is run from a command-line application and supports the
  following flags:

62 63 64
    --auth_host_name: Host name to use when running a local web server
      to handle redirects during OAuth authorization.
      (default: 'localhost')
65

66 67 68 69 70
    --auth_host_port: Port to use when running a local web server to handle
    redirects during OAuth authorization.;
      repeat this option to specify a list of values
      (default: '[8080, 8090]')
      (an integer)
71

72 73 74
    --[no]auth_local_webserver: Run a local web server to handle redirects
      during OAuth authorization.
      (default: 'true')
75

76 77
  Since it uses flags make sure to initialize the gflags module before
  calling run().
78 79 80

  Args:
    flow: Flow, an OAuth 2.0 Flow to step through.
81 82 83
    storage: Storage, a Storage to store the credential in.
    http: An instance of httplib2.Http.request
         or something that acts like it.
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98

  Returns:
    Credentials, the obtained credential.
  """
  logging.warning('This function, oauth2client.tools.run(), and the use of '
      'the gflags library are deprecated and will be removed in a future '
      'version of the library.')
  if FLAGS.auth_local_webserver:
    success = False
    port_number = 0
    for port in FLAGS.auth_host_port:
      port_number = port
      try:
        httpd = ClientRedirectServer((FLAGS.auth_host_name, port),
                                     ClientRedirectHandler)
99
      except socket.error, e:
100 101 102 103 104 105
        pass
      else:
        success = True
        break
    FLAGS.auth_local_webserver = success
    if not success:
106 107 108 109 110 111 112
      print 'Failed to start a local webserver listening on either port 8080'
      print 'or port 9090. Please check your firewall settings and locally'
      print 'running programs that may be blocking or using those ports.'
      print
      print 'Falling back to --noauth_local_webserver and continuing with',
      print 'authorization.'
      print
113 114 115 116 117 118 119 120 121 122

  if FLAGS.auth_local_webserver:
    oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number)
  else:
    oauth_callback = client.OOB_CALLBACK_URN
  flow.redirect_uri = oauth_callback
  authorize_url = flow.step1_get_authorize_url()

  if FLAGS.auth_local_webserver:
    webbrowser.open(authorize_url, new=1, autoraise=True)
123 124 125 126 127 128 129 130 131
    print 'Your browser has been opened to visit:'
    print
    print '    ' + authorize_url
    print
    print 'If your browser is on a different machine then exit and re-run'
    print 'this application with the command-line parameter '
    print
    print '  --noauth_local_webserver'
    print
132
  else:
133 134 135 136
    print 'Go to the following link in your browser:'
    print
    print '    ' + authorize_url
    print
137 138 139 140 141 142 143 144 145

  code = None
  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:
146
      print 'Failed to find "code" in the query parameters of the redirect.'
147 148
      sys.exit('Try running with --noauth_local_webserver.')
  else:
149
    code = raw_input('Enter verification code: ').strip()
150 151 152

  try:
    credential = flow.step2_exchange(code, http=http)
153
  except client.FlowExchangeError, e:
154 155 156 157
    sys.exit('Authentication has failed: %s' % e)

  storage.put(credential)
  credential.set_store(storage)
158
  print 'Authentication successful.'
159

160
  return credential