/src/googlecl/discovery/authentication.py

http://googlecl.googlecode.com/ · Python · 64 lines · 25 code · 6 blank · 33 comment · 4 complexity · 36625ee91479051185b8171b8f48e5ec MD5 · raw file

  1. # 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. """Subfunction for the Google command line tool, GoogleCL.
  15. This function handles the authentication and storage of
  16. credentials for the services which use OAuth2
  17. """
  18. import httplib2
  19. import logging
  20. import pickle
  21. import os
  22. import googlecl
  23. from oauth2client.file import Storage
  24. from oauth2client.client import OAuth2WebServerFlow
  25. from oauth2client.tools import run
  26. LOG = logging.getLogger(googlecl.LOGGER_NAME)
  27. TOKENS_FILENAME_FORMAT = 'dca_%s_%s'
  28. def authenticate(email, servicename, doc, http, client_id,
  29. client_secret, force_auth=False):
  30. """ Authenticates an provided http object,
  31. Prompts for user confirmation if necessary, and stores the credentials
  32. Args:
  33. email: The email address of the user
  34. servicename: The service which requires authentication
  35. doc: Documentation for the service (for determining scopes)
  36. http: The object being authenticated
  37. Returns:
  38. The authorized object
  39. """
  40. tokens_path = googlecl.get_data_path(TOKENS_FILENAME_FORMAT %
  41. (email, servicename),
  42. create_missing_dir=True)
  43. storage = Storage(tokens_path)
  44. credentials = storage.get()
  45. if credentials is None or credentials.invalid or force_auth:
  46. # Works with google-api-python-client-1.0beta2, but not with
  47. # beta4. They're working on a way to allow deleting credentials.
  48. #storage.put(None)
  49. desiredcred = ""
  50. for arg in doc['auth']['oauth2']['scopes']:
  51. desiredcred = desiredcred + arg + ' '
  52. FLOW = OAuth2WebServerFlow(client_id, client_secret,
  53. scope=desiredcred, user_agent='discoverycl')
  54. credentials = run(FLOW, storage)
  55. return credentials.authorize(http)