auth.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. """Wrapper for Google OAuth2 API."""
  2. import sys
  3. import googleapiclient.discovery
  4. import oauth2client
  5. import httplib2
  6. YOUTUBE_UPLOAD_SCOPE = "https://www.googleapis.com/auth/youtube.upload"
  7. def _get_code_from_prompt(authorize_url):
  8. """Show authorization URL and return the code the user wrote."""
  9. message = "Check this link in your browser: {0}".format(authorize_url)
  10. sys.stderr.write(message + "\n")
  11. return raw_input("Enter verification code: ").strip()
  12. def _get_credentials_interactively(flow, storage, get_code_callback):
  13. """Return the credentials asking the user."""
  14. flow.redirect_uri = oauth2client.client.OOB_CALLBACK_URN
  15. authorize_url = flow.step1_get_authorize_url()
  16. code = get_code_callback(authorize_url)
  17. credential = flow.step2_exchange(code, http=None)
  18. storage.put(credential)
  19. credential.set_store(storage)
  20. return credential
  21. def _get_credentials(flow, storage, get_code_callback):
  22. """Return the user credentials. If not found, run the interactive flow."""
  23. existing_credentials = storage.get()
  24. if existing_credentials and not existing_credentials.invalid:
  25. return existing_credentials
  26. else:
  27. return _get_credentials_interactively(flow, storage, get_code_callback)
  28. def get_resource(client_secrets_file, credentials_file, get_code_callback=None):
  29. """Authenticate and return a googleapiclient.discovery.Resource object."""
  30. get_flow = oauth2client.client.flow_from_clientsecrets
  31. flow = get_flow(client_secrets_file, scope=YOUTUBE_UPLOAD_SCOPE)
  32. storage = oauth2client.file.Storage(credentials_file)
  33. get_code = get_code_callback or _get_code_from_prompt
  34. credentials = _get_credentials(flow, storage, get_code)
  35. http = credentials.authorize(httplib2.Http())
  36. return apiclient.discovery.build("youtube", "v3", http=http)