Exemplo n.º 1
0
def _Load(account, scopes, prevent_refresh):
    """Helper for Load()."""
    # If a credential file is set, just use that and ignore the active account
    # and whatever is in the credential store.
    cred_file_override = properties.VALUES.auth.credential_file_override.Get()
    if cred_file_override:
        log.info('Using alternate credentials from file: [%s]',
                 cred_file_override)
        try:
            cred = client.GoogleCredentials.from_stream(cred_file_override)
        except client.Error as e:
            raise InvalidCredentialFileException(cred_file_override, e)

        if cred.create_scoped_required():
            if scopes is None:
                scopes = config.CLOUDSDK_SCOPES
            cred = cred.create_scoped(scopes)

        # Set token_uri after scopes since token_uri needs to be explicitly
        # preserved when scopes are applied.
        token_uri_override = properties.VALUES.auth.token_host.Get()
        if token_uri_override:
            cred_type = creds.CredentialType.FromCredentials(cred)
            if cred_type in (creds.CredentialType.SERVICE_ACCOUNT,
                             creds.CredentialType.P12_SERVICE_ACCOUNT):
                cred.token_uri = token_uri_override
        # The credential override is not stored in credential store, but we still
        # want to cache access tokens between invocations.
        return creds.MaybeAttachAccessTokenCacheStore(cred)

    if not account:
        account = properties.VALUES.core.account.Get()

    if not account:
        raise NoActiveAccountException(
            named_configs.ActiveConfig(False).file_path)

    cred = STATIC_CREDENTIAL_PROVIDERS.GetCredentials(account)
    if cred is not None:
        return cred

    store = creds.GetCredentialStore()
    cred = store.Load(account)
    if not cred:
        raise NoCredentialsForAccountException(account)

    # cred.token_expiry is in UTC time.
    if (not prevent_refresh
            and (not cred.token_expiry
                 or cred.token_expiry < cred.token_expiry.utcnow())):
        Refresh(cred)

    return cred
Exemplo n.º 2
0
 def testAttachAccessTokenCacheStore(self):
   access_token_cache = creds.AccessTokenCache(
       config.Paths().access_token_db_path)
   credentials = creds.FromJson(self.SERVICE_ACCOUNT_CREDENTIALS_JSON)
   credentials.token_response = json.loads("""{"id_token": "woweee"}""")
   self.assertIsNone(credentials.access_token)
   access_token_cache.Store(
       credentials.service_account_email,
       access_token='token1',
       token_expiry=datetime.datetime.utcnow() +
       datetime.timedelta(seconds=3600),
       rapt_token=None,
       id_token=None)
   self.assertIsNone(credentials.access_token)
   new_cred = creds.MaybeAttachAccessTokenCacheStore(credentials)
   self.assertIsNone(new_cred.token_response)
   self.assertEqual('token1', new_cred.access_token)
Exemplo n.º 3
0
def Load(account=None, scopes=None, prevent_refresh=False):
    """Get the credentials associated with the provided account.

  This loads credentials regardless of whether credentials have been disabled
  via properties. Only use this when the functionality of the caller absolutely
  requires credentials (like printing out a token) vs logically requiring
  credentials (like for an http request).

  Args:
    account: str, The account address for the credentials being fetched. If
        None, the account stored in the core.account property is used.
    scopes: tuple, Custom auth scopes to request. By default CLOUDSDK_SCOPES
        are requested.
    prevent_refresh: bool, If True, do not refresh the access token even if it
        is out of date. (For use with operations that do not require a current
        access token, such as credential revocation.)

  Returns:
    oauth2client.client.Credentials, The specified credentials.

  Raises:
    NoActiveAccountException: If account is not provided and there is no
        active account.
    NoCredentialsForAccountException: If there are no valid credentials
        available for the provided or active account.
    c_gce.CannotConnectToMetadataServerException: If the metadata server cannot
        be reached.
    TokenRefreshError: If the credentials fail to refresh.
    TokenRefreshReauthError: If the credentials fail to refresh due to reauth.
  """
    # If a credential file is set, just use that and ignore the active account
    # and whatever is in the credential store.
    cred_file_override = properties.VALUES.auth.credential_file_override.Get()
    if cred_file_override:
        log.info('Using alternate credentials from file: [%s]',
                 cred_file_override)
        try:
            cred = client.GoogleCredentials.from_stream(cred_file_override)
        except client.Error as e:
            raise InvalidCredentialFileException(cred_file_override, e)

        if cred.create_scoped_required():
            if scopes is None:
                scopes = config.CLOUDSDK_SCOPES
            cred = cred.create_scoped(scopes)

        # Set token_uri after scopes since token_uri needs to be explicitly
        # preserved when scopes are applied.
        token_uri_override = properties.VALUES.auth.token_host.Get()
        if token_uri_override:
            cred_type = creds.CredentialType.FromCredentials(cred)
            if cred_type in (creds.CredentialType.SERVICE_ACCOUNT,
                             creds.CredentialType.P12_SERVICE_ACCOUNT):
                cred.token_uri = token_uri_override
        # The credential override is not stored in credential store, but we still
        # want to cache access tokens between invocations.
        return creds.MaybeAttachAccessTokenCacheStore(cred)

    if not account:
        account = properties.VALUES.core.account.Get()

    if not account:
        raise NoActiveAccountException()

    cred = STATIC_CREDENTIAL_PROVIDERS.GetCredentials(account)
    if cred is not None:
        return cred

    store = creds.GetCredentialStore()
    cred = store.Load(account)
    if not cred:
        raise NoCredentialsForAccountException(account)

    # cred.token_expiry is in UTC time.
    if (not prevent_refresh
            and (not cred.token_expiry
                 or cred.token_expiry < cred.token_expiry.utcnow())):
        Refresh(cred)

    return cred