How to use the oauth2client.client.OAuth2Credentials function in oauth2client

To help you get started, we’ve selected a few oauth2client examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github googleapis / oauth2client / tests / contrib / test_dictionary_storage.py View on Github external
def _generate_credentials(scopes=None):
    return client.OAuth2Credentials(
        'access_tokenz',
        'client_idz',
        'client_secretz',
        'refresh_tokenz',
        '3600',
        oauth2client.GOOGLE_TOKEN_URI,
        'Test',
        id_token={
            'sub': '123',
            'email': 'user@example.com'
        },
        scopes=scopes)
github googleapis / oauth2client / tests / test_client.py View on Github external
def _do_revoke_test_helper(self, response, content,
                               error_msg, logger, store=None):
        credentials = client.OAuth2Credentials(
            None, None, None, None, None, None, None,
            revoke_uri=oauth2client.GOOGLE_REVOKE_URI)
        credentials.store = store

        http = http_mock.HttpMock(headers=response, data=content)
        token = u's3kr3tz'

        if response.status == http_client.OK:
            self.assertFalse(credentials.invalid)
            self.assertIsNone(credentials._do_revoke(http, token))
            self.assertTrue(credentials.invalid)
            if store is not None:
                store.delete.assert_called_once_with()
        else:
            self.assertFalse(credentials.invalid)
            with self.assertRaises(client.TokenRevokeError) as exc_manager:
github googleapis / oauth2client / tests / test_client.py View on Github external
def _do_refresh_request_test_helper(self, response, content,
                                        error_msg, logger, gen_body,
                                        gen_headers, store=None):
        token_uri = 'http://token_uri'
        credentials = client.OAuth2Credentials(None, None, None, None,
                                               None, token_uri, None)
        credentials.store = store
        http = http_mock.HttpMock(headers=response, data=content)

        with self.assertRaises(
                client.HttpAccessTokenRefreshError) as exc_manager:
            credentials._do_refresh_request(http)

        self.assertEqual(exc_manager.exception.args, (error_msg,))
        self.assertEqual(exc_manager.exception.status, response.status)

        # Verify mocks.
        self.assertEqual(http.requests, 1)
        self.assertEqual(http.uri, token_uri)
        self.assertEqual(http.method, 'POST')
        self.assertEqual(http.body, gen_body.return_value)
github google / starthinker / starthinker / util / auth / google_bucket_auth.py View on Github external
super(BucketStorage, self).__init__()
    self.cloud_path = cloud_path

  def locked_get(self):
    return BucketCredentials.from_json(credentails_get(self.cloud_path))

  def locked_put(self, credentials):
    credentails_put(self.cloud_path, credentials.to_json())

  def locked_delete(self):
    return # skip for now until tested well
    #service = get_service()
    #bucket, filename = self.cloud_path.split(':',1)
    #service.objects().delete(bucket=bucket, object=filename).execute()

class BucketCredentials(OAuth2Credentials):

  def __init__(self, *args, **kwargs):
    self.cloud_path = kwargs.pop('cloud_path')
    super(BucketCredentials, self).__init__(*args, **kwargs)
    self.store = BucketStorage(self.cloud_path)

  def set_cloud_path(self, cloud_path):
    self.cloud_path = cloud_path

  @classmethod
  def from_json(cls, json_data):
    data = json.loads(_helpers._from_bytes(json_data))
    if (data.get('token_expiry') and not isinstance(data['token_expiry'], datetime.datetime)):
      try: data['token_expiry'] = datetime.datetime.strptime(data['token_expiry'], EXPIRY_FORMAT)
      except ValueError: data['token_expiry'] = None
github puiterwijk / flask-oidc / flask_oidc / __init__.py View on Github external
:returns: The contents of the UserInfo endpoint.
        :rtype: dict
        """
        if 'userinfo_uri' not in self.client_secrets:
            logger.debug('Userinfo uri not specified')
            raise AssertionError('UserInfo URI not specified')

        # Cache the info from this request
        if '_oidc_userinfo' in g:
            return g._oidc_userinfo

        http = httplib2.Http()
        if access_token is None:
            try:
                credentials = OAuth2Credentials.from_json(
                    self.credentials_store[g.oidc_id_token['sub']])
            except KeyError:
                logger.debug("Expired ID token, credentials missing",
                             exc_info=True)
                return None
            credentials.authorize(http)
            resp, content = http.request(self.client_secrets['userinfo_uri'])
        else:
            # We have been manually overriden with an access token
            resp, content = http.request(
                self.client_secrets['userinfo_uri'],
                "POST",
                body=urlencode({"access_token": access_token}),
                headers={'Content-Type': 'application/x-www-form-urlencoded'})

        logger.debug('Retrieved user info: %s' % content)
github Ajapaik / ajapaik-web / project / ajapaik / models.py View on Github external
def update_from_google_plus_data(self, token, data):
        # TODO: Make form
        if 'given_name' in data:
            self.user.first_name = data["given_name"]
        if 'family_name' in data:
            self.user.last_name = data["family_name"]
        self.user.save()

        if isinstance(token, OAuth2Credentials):
            self.google_plus_token = loads(token.to_json())['access_token']
        else:
            self.google_plus_token = token
        self.google_plus_id = data["id"]
        if 'link' in data:
            self.google_plus_link = data["link"]
        if 'name' in data:
            self.google_plus_name = data["name"]
        if 'email' in data:
            self.google_plus_email = data["email"]
        if 'picture' in data:
            self.google_plus_picture = data["picture"]
        self.save()
github GoogleCloudPlatform / gsutil / gslib / gcs_json_credentials.py View on Github external
key_parts.append(credentials.user_email)
  elif isinstance(credentials, ServiceAccountCredentials):
    # pylint: disable=protected-access
    key_parts.append(credentials._service_account_email)
    if getattr(credentials, '_private_key_id', None):  # JSON keyfile.
      # Differentiate between two different JSON keyfiles for the same service
      # account.
      key_parts.append(credentials._private_key_id)
    elif getattr(credentials, '_private_key_pkcs12', None):  # P12 keyfile
      # Use a prefix of the Base64-encoded PEM string to differentiate it from
      # others. Using a prefix of reasonable length prevents the key from being
      # unnecessarily large, and the likelihood of having two PEM strings with
      # the same prefixes is sufficiently low.
      key_parts.append(base64.b64encode(credentials._private_key_pkcs12)[:20])
    # pylint: enable=protected-access
  elif isinstance(credentials, oauth2client.client.OAuth2Credentials):
    if credentials.client_id and credentials.client_id != 'null':
      key_parts.append(credentials.client_id)
    else:
      key_parts.append('noclientid')
    key_parts.append(credentials.refresh_token or 'norefreshtoken')

  # If a cached credential is targeting provider token URI 'A' for token refresh
  # requests, then the user changes their boto file or private key file to
  # target URI 'B', we don't want to treat the cached and the new credential as
  # interchangeable.  This applies for all credentials that store a token URI.
  if getattr(credentials, 'token_uri', None):
    key_parts.append(credentials.token_uri)
  key_parts = [six.ensure_text(part) for part in key_parts]
  return '-'.join(key_parts)
github adamhub / nebri / google-drive / google_update_spreadsheet.py View on Github external
def action(self):
        credentials = OAuth2Credentials.from_json(shared.client_credentials)
        gc = gspread.authorize(credentials)
        
        # get worksheet
        sh = gc.open(shared.update_gsheet['filename'])
        worksheet = sh.get_worksheet(0)

        # data
        datalist = shared.update_gsheet['data']

        # loop through each data for row
        row = 1
        for k in range(0, len(datalist)):
            col_num = len(datalist[k])
            col_letter = chr(ord('A') + col_num - 1)

            row_range = 'A{row}:{col}{row}'.format(row=row, col=col_letter)
github GoogleCloudPlatform / python-compat-runtime / python_vm_runtime / google / appengine / tools / appengine_rpc_httplib2.py View on Github external
if save_cookies:
      oauth2_credential_file = (oauth2_parameters.credential_file
                                or '~/.appcfg_oauth2_tokens')
      self.storage = oauth2client_file.Storage(
          os.path.expanduser(oauth2_credential_file))
    else:
      self.storage = NoStorage()

    if oauth2_parameters.credentials:
      self.credentials = oauth2_parameters.credentials
    elif any((oauth2_parameters.access_token, oauth2_parameters.refresh_token,
              oauth2_parameters.token_uri)):
      token_uri = (oauth2_parameters.token_uri or
                   ('https://%s/o/oauth2/token' %
                    os.getenv('APPENGINE_AUTH_SERVER', 'accounts.google.com')))
      self.credentials = client.OAuth2Credentials(
          oauth2_parameters.access_token,
          oauth2_parameters.client_id,
          oauth2_parameters.client_secret,
          oauth2_parameters.refresh_token,
          None,
          token_uri,
          self.user_agent)
    else:
      self.credentials = self.storage.get()

    self.flags = self.FlowFlags(options)
github googledatalab / pydatalab / google / datalab / utils / _utils.py View on Github external
authDefaultLogger.setLevel(logging.ERROR)
    credentials, _ = google.auth.default()
    credentials = google.auth.credentials.with_scopes_if_required(credentials, CREDENTIAL_SCOPES)
    authDefaultLogger.setLevel(previousLevel)
    return credentials
  except Exception as e:

    # Try load user creds from file
    cred_file = get_config_dir() + '/credentials'
    if os.path.exists(cred_file):
      with open(cred_file) as f:
        creds = json.loads(f.read())
      # Use the first gcloud one we find
      for entry in creds['data']:
        if entry['key']['type'] == 'google-cloud-sdk':
          creds = oauth2client.client.OAuth2Credentials.from_json(json.dumps(entry['credential']))
          return _convert_oauth2client_creds(creds)

    if type(e) == google.auth.exceptions.DefaultCredentialsError:
      # If we are in Datalab container, change the message to be about signing in.
      if _in_datalab_docker():
        raise Exception('No application credentials found. Perhaps you should sign in.')

    raise e