Python oauth2client.client() Examples

The following are 30 code examples of oauth2client.client(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module oauth2client , or try the search function .
Example #1
Source File: httplib2_utils.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def __init__(self, http, service_account_email, scopes, project='-'):
    """
    Args:
      http: An httplib2.Http object that is authorized by another
        oauth2client.client.OAuth2Credentials with credentials that have the
        service account token creator role on the service_account_email.
      service_account_email: The email address of the service account for which
        to obtain an access token.
      scopes: The desired scopes for the token.
      project: The cloud project to which service_account_email belongs.  The
        default of '-' makes the IAM API figure it out for us.
    """

    super(DelegateServiceAccountCredentials, self).__init__(
        None, None, None, None, None, None, None)

    self._http = http
    self._sa_email = service_account_email
    self._scopes = self._canonicalize_scopes(scopes)
    self._project = project

    self.token_expiry = None
    self.access_token = None 
Example #2
Source File: _auth.py    From alfred-gmail with MIT License 6 votes vote down vote up
def with_scopes(credentials, scopes):
    """Scopes the credentials if necessary.

    Args:
        credentials (Union[
            google.auth.credentials.Credentials,
            oauth2client.client.Credentials]): The credentials to scope.
        scopes (Sequence[str]): The list of scopes.

    Returns:
        Union[google.auth.credentials.Credentials,
            oauth2client.client.Credentials]: The scoped credentials.
    """
    if HAS_GOOGLE_AUTH and isinstance(
            credentials, google.auth.credentials.Credentials):
        return google.auth.credentials.with_scopes_if_required(
            credentials, scopes)
    else:
        try:
            if credentials.create_scoped_required():
                return credentials.create_scoped(scopes)
            else:
                return credentials
        except AttributeError:
            return credentials 
Example #3
Source File: credentials_lib.py    From apitools with Apache License 2.0 6 votes vote down vote up
def ServiceAccountCredentialsFromP12File(
        service_account_name, private_key_filename, scopes, user_agent):
    """Create a new credential from the named .p12 keyfile."""
    private_key_filename = os.path.expanduser(private_key_filename)
    scopes = util.NormalizeScopes(scopes)
    if oauth2client.__version__ > '1.5.2':
        # oauth2client >= 2.0.0
        credentials = (
            service_account.ServiceAccountCredentials.from_p12_keyfile(
                service_account_name, private_key_filename, scopes=scopes))
        if credentials is not None:
            credentials.user_agent = user_agent
        return credentials
    else:
        # oauth2client < 2.0.0
        with open(private_key_filename, 'rb') as key_file:
            return oauth2client.client.SignedJwtAssertionCredentials(
                service_account_name, key_file.read(), scopes,
                user_agent=user_agent) 
Example #4
Source File: httplib2_utils.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def __init__(self, http, service_account_email, scopes, project='-'):
    """
    Args:
      http: An httplib2.Http object that is authorized by another
        oauth2client.client.OAuth2Credentials with credentials that have the
        service account actor role on the service_account_email.
      service_account_email: The email address of the service account for which
        to obtain an access token.
      scopes: The desired scopes for the token.
      project: The cloud project to which service_account_email belongs.  The
        default of '-' makes the IAM API figure it out for us.
    """

    super(DelegateServiceAccountCredentials, self).__init__(None)
    self._service_account_email = service_account_email
    self._scopes = util.scopes_to_string(scopes)
    self._http = http
    self._name = 'projects/%s/serviceAccounts/%s' % (
        project, service_account_email) 
Example #5
Source File: credentials_lib.py    From apitools with Apache License 2.0 6 votes vote down vote up
def GetUserinfo(credentials, http=None):  # pylint: disable=invalid-name
    """Get the userinfo associated with the given credentials.

    This is dependent on the token having either the userinfo.email or
    userinfo.profile scope for the given token.

    Args:
      credentials: (oauth2client.client.Credentials) incoming credentials
      http: (httplib2.Http, optional) http instance to use

    Returns:
      The email address for this token, or None if the required scopes
      aren't available.
    """
    http = http or httplib2.Http()
    url = _GetUserinfoUrl(credentials)
    # We ignore communication woes here (i.e. SSL errors, socket
    # timeout), as handling these should be done in a common location.
    response, content = http.request(url)
    if response.status == http_client.BAD_REQUEST:
        credentials.refresh(http)
        url = _GetUserinfoUrl(credentials)
        response, content = http.request(url)
    return json.loads(content or '{}')  # Save ourselves from an empty reply. 
Example #6
Source File: credentials_lib.py    From apitools with Apache License 2.0 6 votes vote down vote up
def GetCredentials(package_name, scopes, client_id, client_secret, user_agent,
                   credentials_filename=None,
                   api_key=None,  # pylint: disable=unused-argument
                   client=None,  # pylint: disable=unused-argument
                   oauth2client_args=None,
                   **kwds):
    """Attempt to get credentials, using an oauth dance as the last resort."""
    scopes = util.NormalizeScopes(scopes)
    client_info = {
        'client_id': client_id,
        'client_secret': client_secret,
        'scope': ' '.join(sorted(scopes)),
        'user_agent': user_agent or '%s-generated/0.1' % package_name,
    }
    for method in _CREDENTIALS_METHODS:
        credentials = method(client_info, **kwds)
        if credentials is not None:
            return credentials
    credentials_filename = credentials_filename or os.path.expanduser(
        '~/.apitools.token')
    credentials = CredentialsFromFile(credentials_filename, client_info,
                                      oauth2client_args=oauth2client_args)
    if credentials is not None:
        return credentials
    raise exceptions.CredentialsError('Could not create valid credentials') 
Example #7
Source File: httplib2_utils.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def __init__(self, http, service_account_email, scopes, project='-'):
    """
    Args:
      http: An httplib2.Http object that is authorized by another
        oauth2client.client.OAuth2Credentials with credentials that have the
        service account token creator role on the service_account_email.
      service_account_email: The email address of the service account for which
        to obtain an access token.
      scopes: The desired scopes for the token.
      project: The cloud project to which service_account_email belongs.  The
        default of '-' makes the IAM API figure it out for us.
    """

    super(DelegateServiceAccountCredentials, self).__init__(
        None, None, None, None, None, None, None)

    self._http = http
    self._sa_email = service_account_email
    self._scopes = self._canonicalize_scopes(scopes)
    self._project = project

    self.token_expiry = None
    self.access_token = None 
Example #8
Source File: credentials_lib.py    From apitools with Apache License 2.0 6 votes vote down vote up
def from_json(cls, json_data):
        data = json.loads(json_data)
        kwargs = {}
        if 'cache_filename' in data.get('kwargs', []):
            kwargs['cache_filename'] = data['kwargs']['cache_filename']
        # Newer versions of GceAssertionCredentials don't have a "scope"
        # attribute.
        scope_list = None
        if 'scope' in data:
            scope_list = [data['scope']]
        credentials = GceAssertionCredentials(scopes=scope_list, **kwargs)
        if 'access_token' in data:
            credentials.access_token = data['access_token']
        if 'token_expiry' in data:
            credentials.token_expiry = datetime.datetime.strptime(
                data['token_expiry'], oauth2client.client.EXPIRY_FORMAT)
        if 'invalid' in data:
            credentials.invalid = data['invalid']
        return credentials 
Example #9
Source File: upload.py    From gmail-yaml-filters with MIT License 6 votes vote down vote up
def get_gmail_credentials(
    scopes=[
        'https://www.googleapis.com/auth/gmail.settings.basic',
        'https://www.googleapis.com/auth/gmail.labels',
    ],
    client_secret_path='client_secret.json',
    application_name='gmail_yaml_filters',
):
    credential_dir = os.path.join(os.path.expanduser('~'), '.credentials')
    credential_path = os.path.join(credential_dir, application_name + '.json')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = oauth2client.client.flow_from_clientsecrets(client_secret_path, scopes)
        flow.user_agent = application_name
        flags_parser = argparse.ArgumentParser(parents=[oauth2client.tools.argparser])
        credentials = oauth2client.tools.run_flow(flow, store, flags=flags_parser.parse_args([]))
        print('Storing credentials to', credential_path, file=sys.stderr)

    return credentials 
Example #10
Source File: httplib2_utils.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def __init__(self, http, service_account_email, scopes, project='-'):
    """
    Args:
      http: An httplib2.Http object that is authorized by another
        oauth2client.client.OAuth2Credentials with credentials that have the
        service account actor role on the service_account_email.
      service_account_email: The email address of the service account for which
        to obtain an access token.
      scopes: The desired scopes for the token.
      project: The cloud project to which service_account_email belongs.  The
        default of '-' makes the IAM API figure it out for us.
    """

    super(DelegateServiceAccountCredentials, self).__init__(None)
    self._service_account_email = service_account_email
    self._scopes = util.scopes_to_string(scopes)
    self._http = http
    self._name = 'projects/%s/serviceAccounts/%s' % (
        project, service_account_email) 
Example #11
Source File: httplib2_utils.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def __init__(self, http, service_account_email, scopes, project='-'):
    """
    Args:
      http: An httplib2.Http object that is authorized by another
        oauth2client.client.OAuth2Credentials with credentials that have the
        service account token creator role on the service_account_email.
      service_account_email: The email address of the service account for which
        to obtain an access token.
      scopes: The desired scopes for the token.
      project: The cloud project to which service_account_email belongs.  The
        default of '-' makes the IAM API figure it out for us.
    """

    super(DelegateServiceAccountCredentials, self).__init__(
        None, None, None, None, None, None, None)

    self._http = http
    self._sa_email = service_account_email
    self._scopes = self._canonicalize_scopes(scopes)
    self._project = project

    self.token_expiry = None
    self.access_token = None 
Example #12
Source File: gmc_export.py    From ebola-tools with Apache License 2.0 6 votes vote down vote up
def authorize(flags, scope, client_secrets_path, credentials_path):
    """Authorizes an HTTP object with the user's credentials.

    Args:
        flags: Command-line flags from argparse.ArgumentParser.parse_args().
        scope: OAuth scope URL.
        client_secret_path: Path to an existing client_secrets.json file.
        credentials_path: Path where the user's credentials are stored; if
            this file doesn't exist yet, the user will be taken through the
            consent flow and then the credentials will be saved here.
    """
    storage = oauth2client.file.Storage(credentials_path)
    credentials = storage.get()
    if not credentials or credentials.invalid:
        flow = oauth2client.client.flow_from_clientsecrets(
            client_secrets_path, scope=scope,
            message=oauth2client.tools.message_if_missing(client_secrets_path))
        credentials = oauth2client.tools.run_flow(flow, storage, flags)
    return credentials.authorize(httplib2.Http()) 
Example #13
Source File: httplib2_utils.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def __init__(self, http, service_account_email, scopes, project='-'):
    """
    Args:
      http: An httplib2.Http object that is authorized by another
        oauth2client.client.OAuth2Credentials with credentials that have the
        service account token creator role on the service_account_email.
      service_account_email: The email address of the service account for which
        to obtain an access token.
      scopes: The desired scopes for the token.
      project: The cloud project to which service_account_email belongs.  The
        default of '-' makes the IAM API figure it out for us.
    """

    super(DelegateServiceAccountCredentials, self).__init__(
        None, None, None, None, None, None, None)

    self._http = http
    self._sa_email = service_account_email
    self._scopes = self._canonicalize_scopes(scopes)
    self._project = project

    self.token_expiry = None
    self.access_token = None 
Example #14
Source File: httplib2_utils.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def __init__(self, http, service_account_email, scopes, project='-'):
    """
    Args:
      http: An httplib2.Http object that is authorized by another
        oauth2client.client.OAuth2Credentials with credentials that have the
        service account actor role on the service_account_email.
      service_account_email: The email address of the service account for which
        to obtain an access token.
      scopes: The desired scopes for the token.
      project: The cloud project to which service_account_email belongs.  The
        default of '-' makes the IAM API figure it out for us.
    """

    super(DelegateServiceAccountCredentials, self).__init__(None)
    self._service_account_email = service_account_email
    self._scopes = util.scopes_to_string(scopes)
    self._http = http
    self._name = 'projects/%s/serviceAccounts/%s' % (
        project, service_account_email) 
Example #15
Source File: django_orm.py    From sndlatr with Apache License 2.0 6 votes vote down vote up
def to_python(self, value):
    if value is None:
      return None
    if isinstance(value, oauth2client.client.Credentials):
      return value
    return pickle.loads(base64.b64decode(value)) 
Example #16
Source File: httplib2_utils.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def __init__(self, http, service_account_email, scopes, project='-'):
    """
    Args:
      http: An httplib2.Http object that is authorized by another
        oauth2client.client.OAuth2Credentials with credentials that have the
        service account actor role on the service_account_email.
      service_account_email: The email address of the service account for which
        to obtain an access token.
      scopes: The desired scopes for the token.
      project: The cloud project to which service_account_email belongs.  The
        default of '-' makes the IAM API figure it out for us.
    """

    super(DelegateServiceAccountCredentials, self).__init__(None)
    self._service_account_email = service_account_email
    self._scopes = util.scopes_to_string(scopes)
    self._http = http
    self._name = 'projects/%s/serviceAccounts/%s' % (
        project, service_account_email) 
Example #17
Source File: django_orm.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def to_python(self, value):
    if value is None:
      return None
    if isinstance(value, oauth2client.client.Credentials):
      return value
    return pickle.loads(base64.b64decode(value)) 
Example #18
Source File: django_orm.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def to_python(self, value):
        if value is None:
            return None
        if isinstance(value, oauth2client.client.Credentials):
            return value
        return pickle.loads(base64.b64decode(smart_bytes(value))) 
Example #19
Source File: django_orm.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def to_python(self, value):
        if value is None:
            return None
        if isinstance(value, oauth2client.client.Flow):
            return value
        return pickle.loads(base64.b64decode(value)) 
Example #20
Source File: django_orm.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def to_python(self, value):
    if value is None:
      return None
    if isinstance(value, oauth2client.client.Flow):
      return value
    return pickle.loads(base64.b64decode(value)) 
Example #21
Source File: credentials_lib.py    From apitools with Apache License 2.0 5 votes vote down vote up
def _GetApplicationDefaultCredentials(
        client_info, skip_application_default_credentials=False,
        **unused_kwds):
    """Returns ADC with right scopes."""
    scopes = client_info['scope'].split()
    if skip_application_default_credentials:
        return None
    gc = oauth2client.client.GoogleCredentials
    with cache_file_lock:
        try:
            # pylint: disable=protected-access
            # We've already done our own check for GAE/GCE
            # credentials, we don't want to pay for checking again.
            credentials = gc._implicit_credentials_from_files()
        except oauth2client.client.ApplicationDefaultCredentialsError:
            return None
    # If we got back a non-service account credential, we need to use
    # a heuristic to decide whether or not the application default
    # credential will work for us. We assume that if we're requesting
    # cloud-platform, our scopes are a subset of cloud scopes, and the
    # ADC will work.
    cp = 'https://www.googleapis.com/auth/cloud-platform'
    if credentials is None:
        return None
    if not isinstance(credentials, gc) or cp in scopes:
        return credentials.create_scoped(scopes)
    return None 
Example #22
Source File: client.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def _get_application_default_credential_from_file(filename):
    """Build the Application Default Credentials from file."""
    # read the credentials from the file
    with open(filename) as file_obj:
        client_credentials = json.load(file_obj)

    credentials_type = client_credentials.get('type')
    if credentials_type == AUTHORIZED_USER:
        required_fields = set(['client_id', 'client_secret', 'refresh_token'])
    elif credentials_type == SERVICE_ACCOUNT:
        required_fields = set(['client_id', 'client_email', 'private_key_id',
                               'private_key'])
    else:
        raise ApplicationDefaultCredentialsError(
            "'type' field should be defined (and have one of the '" +
            AUTHORIZED_USER + "' or '" + SERVICE_ACCOUNT + "' values)")

    missing_fields = required_fields.difference(client_credentials.keys())

    if missing_fields:
        _raise_exception_for_missing_fields(missing_fields)

    if client_credentials['type'] == AUTHORIZED_USER:
        return GoogleCredentials(
            access_token=None,
            client_id=client_credentials['client_id'],
            client_secret=client_credentials['client_secret'],
            refresh_token=client_credentials['refresh_token'],
            token_expiry=None,
            token_uri=oauth2client.GOOGLE_TOKEN_URI,
            user_agent='Python client library')
    else:  # client_credentials['type'] == SERVICE_ACCOUNT
        from oauth2client import service_account
        return service_account._JWTAccessCredentials.from_json_keyfile_dict(
            client_credentials) 
Example #23
Source File: credentials_lib.py    From apitools with Apache License 2.0 5 votes vote down vote up
def _refresh(self, do_request):
        """Refresh self.access_token.

        This function replaces AppAssertionCredentials._refresh, which
        does not use the credential store and is therefore poorly
        suited for multi-threaded scenarios.

        Args:
          do_request: A function matching httplib2.Http.request's signature.

        """
        # pylint: disable=protected-access
        oauth2client.client.OAuth2Credentials._refresh(self, do_request)
        # pylint: enable=protected-access 
Example #24
Source File: credentials_lib.py    From apitools with Apache License 2.0 5 votes vote down vote up
def ServiceAccountCredentialsFromFile(filename, scopes, user_agent=None):
    """Use the credentials in filename to create a token for scopes."""
    filename = os.path.expanduser(filename)
    # We have two options, based on our version of oauth2client.
    if oauth2client.__version__ > '1.5.2':
        # oauth2client >= 2.0.0
        credentials = (
            service_account.ServiceAccountCredentials.from_json_keyfile_name(
                filename, scopes=scopes))
        if credentials is not None:
            if user_agent is not None:
                credentials.user_agent = user_agent
        return credentials
    else:
        # oauth2client < 2.0.0
        with open(filename) as keyfile:
            service_account_info = json.load(keyfile)
        account_type = service_account_info.get('type')
        if account_type != oauth2client.client.SERVICE_ACCOUNT:
            raise exceptions.CredentialsError(
                'Invalid service account credentials: %s' % (filename,))
        # pylint: disable=protected-access
        credentials = service_account._ServiceAccountCredentials(
            service_account_id=service_account_info['client_id'],
            service_account_email=service_account_info['client_email'],
            private_key_id=service_account_info['private_key_id'],
            private_key_pkcs8_text=service_account_info['private_key'],
            scopes=scopes, user_agent=user_agent)
        # pylint: enable=protected-access
        return credentials 
Example #25
Source File: docker_creds_.py    From containerregistry with Apache License 2.0 5 votes vote down vote up
def password(self):
    # WORKAROUND...
    # The python oauth2client library only loads the credential from an
    # on-disk cache the first time 'refresh()' is called, and doesn't
    # actually 'Force a refresh of access_token' as advertised.
    # This call will load the credential, and the call below will refresh
    # it as needed.  If the credential is unexpired, the call below will
    # simply return a cache of this refresh.
    unused_at = self._creds.get_access_token(http=self._transport)

    # Most useful API ever:
    # https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={at}
    return self._creds.get_access_token(http=self._transport).access_token 
Example #26
Source File: api.py    From professional-services with Apache License 2.0 5 votes vote down vote up
def __get__(self, instance, instance_type):
        """Construct the API client."""
        if instance is None:
            return self

        thread_local = None
        try:
            app = webapp2.get_app()
            # Python Google API clients aren't threadsafe as they use httplib2
            # which isn't threadsafe.
            thread_local = app.registry.get(self)
            if thread_local is None:
                thread_local = threading.local()
                app.registry[self] = thread_local
        except AssertionError:
            # When not in a request context, use class thread local.
            thread_local = ThreadsafeClientLocal._class_thread_local

        cached_client = getattr(thread_local, 'api', None)
        if cached_client is None:
            credentials = client.GoogleCredentials.get_application_default()
            if credentials.create_scoped_required():
                credentials = credentials.create_scoped(
                    'https://www.googleapis.com/auth/cloud-platform')
            cached_client = discovery.build(
                self.service,
                self.version,
                http=credentials.authorize(self.http),
                cache_discovery=self.cache_discovery)
            thread_local.api = cached_client
        return cached_client 
Example #27
Source File: api.py    From professional-services with Apache License 2.0 5 votes vote down vote up
def __init__(self, service, version):
        """Create a thread local API client.

        Will create the underlying httplib2.Http object on construction, but
        the underlying API client is lazy constructed.

        Args:
            service: Name of API.
            version: Version of the api.
        """
        self.service = service
        self.version = version
        self.http = httplib2.Http(timeout=60)
        self.cache_discovery = True 
Example #28
Source File: django_orm.py    From twitter-for-bigquery with Apache License 2.0 5 votes vote down vote up
def to_python(self, value):
    if value is None:
      return None
    if isinstance(value, oauth2client.client.Flow):
      return value
    return pickle.loads(base64.b64decode(value)) 
Example #29
Source File: django_orm.py    From twitter-for-bigquery with Apache License 2.0 5 votes vote down vote up
def to_python(self, value):
    if value is None:
      return None
    if isinstance(value, oauth2client.client.Credentials):
      return value
    return pickle.loads(base64.b64decode(value)) 
Example #30
Source File: httplib2_utils.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def get_signed_jwt_assertion_credentials(credentials_filename,
                                         scope=None,
                                         service_accounts_creds_root=None):
  """Factory for SignedJwtAssertionCredentials

  Reads and validate the json credential file.

  Args:
    credentials_filename (str): path to the service account key file.
      See load_service_account_credentials() docstring for the file format.

  Keyword Args:
    scope (str|list of str): scope(s) of the credentials being
      requested. Defaults to https://www.googleapis.com/auth/userinfo.email.
    service_accounts_creds_root (str or None): location where all service
      account credentials are stored. ``credentials_filename`` is relative
      to this path. None means 'use default location'.
  """
  scope = scope or DEFAULT_SCOPES
  if isinstance(scope, basestring):
    scope = [scope]
  assert all(isinstance(s, basestring) for s in scope)

  key = load_service_account_credentials(
    credentials_filename,
    service_accounts_creds_root=service_accounts_creds_root)

  return oauth2client.client.SignedJwtAssertionCredentials(
    key['client_email'], key['private_key'], scope)