Exemplo n.º 1
0
    def __init__(self, scopes=None, service_account_name='default', **kwds):
        """Initializes the credentials instance.

    Args:
      scopes: The scopes to get. If None, whatever scopes that are available
              to the instance are used.
      service_account_name: The service account to retrieve the scopes from.
      **kwds: Additional keyword args.
    """
        if not util.DetectGce():
            raise exceptions.ResourceUnavailableError(
                'GCE credentials requested outside a GCE instance')
        if not self.GetServiceAccount(service_account_name):
            raise exceptions.ResourceUnavailableError(
                'GCE credentials requested but service account %s does not exist.'
                % service_account_name)
        self.__service_account_name = service_account_name
        if scopes:
            scope_ls = util.NormalizeScopes(scopes)
            instance_scopes = self.GetInstanceScopes()
            if scope_ls > instance_scopes:
                raise exceptions.CredentialsError(
                    'Instance did not have access to scopes %s' %
                    (sorted(list(scope_ls - instance_scopes)), ))
        else:
            scopes = self.GetInstanceScopes()
        super(GceAssertionCredentials, self).__init__(scopes, **kwds)
Exemplo n.º 2
0
def CredentialsFromFile(path, client_info):
    """Read credentials from a file."""
    credential_store = oauth2client.multistore_file.get_credential_storage(
        path, client_info['client_id'], client_info['user_agent'],
        client_info['scope'])
    credentials = credential_store.get()
    if credentials is None or credentials.invalid:
        print 'Generating new OAuth credentials ...'
        while True:
            # If authorization fails, we want to retry, rather than let this
            # cascade up and get caught elsewhere. If users want out of the
            # retry loop, they can ^C.
            try:
                flow = oauth2client.client.OAuth2WebServerFlow(**client_info)
                flow.redirect_uri = oauth2client.client.OOB_CALLBACK_URN
                authorize_url = flow.step1_get_authorize_url()
                print 'Go to the following link in your browser:'
                print
                print '    ' + authorize_url
                print
                code = raw_input('Enter verification code: ').strip()
                credential = flow.step2_exchange(code)
                credential_store.put(credential)
                credential.set_store(credential_store)
                break
            except (oauth2client.client.FlowExchangeError, SystemExit) as e:
                # Here SystemExit is "no credential at all", and the
                # FlowExchangeError is "invalid" -- usually because you reused
                # a token.
                print 'Invalid authorization: %s' % (e, )
            except httplib2.HttpLib2Error as e:
                print 'Communication error: %s' % (e, )
                raise exceptions.CredentialsError(
                    'Communication error creating credentials: %s' % e)
    return credentials
Exemplo n.º 3
0
    def _refresh(self, _):  # pylint: disable=g-bad-name
        """Refresh self.access_token.

    Args:
      _: (ignored) A function matching httplib2.Http.request's signature.
    """
        # pylint: disable=g-import-not-at-top
        from google.appengine.api import app_identity
        try:
            token, _ = app_identity.get_access_token(self._scopes)
        except app_identity.Error as e:
            raise exceptions.CredentialsError(str(e))
        self.access_token = token
Exemplo n.º 4
0
    def _refresh(self, do_request):  # pylint: disable=g-bad-name
        """Refresh self.access_token.

    Args:
      do_request: A function matching httplib2.Http.request's signature.
    """
        token_uri = (
            'http://metadata.google.internal/computeMetadata/v1/instance/'
            'service-accounts/%s/token') % self.__service_account_name
        extra_headers = {'X-Google-Metadata-Request': 'True'}
        request = urllib2.Request(token_uri, headers=extra_headers)
        try:
            content = urllib2.urlopen(request).read()
        except urllib2.URLError as e:
            raise exceptions.CommunicationError(
                'Could not reach metadata service: %s' % e.reason)
        try:
            credential_info = json.loads(content)
        except ValueError:
            raise exceptions.CredentialsError(
                'Invalid credentials response: uri %s' % token_uri)

        self.access_token = credential_info['access_token']
Exemplo n.º 5
0
def GetCredentials(package_name,
                   scopes,
                   client_id,
                   client_secret,
                   user_agent,
                   credentials_filename=None,
                   service_account_name=None,
                   service_account_keyfile=None,
                   api_key=None,
                   client=None):
    """Attempt to get credentials, using an oauth dance as the last resort."""
    scopes = util.NormalizeScopes(scopes)
    # TODO: Error checking.
    client_info = {
        'client_id': client_id,
        'client_secret': client_secret,
        'scope': ' '.join(sorted(util.NormalizeScopes(scopes))),
        'user_agent': user_agent or '%s-generated/0.1' % package_name,
    }
    if service_account_name is not None:
        credentials = ServiceAccountCredentialsFromFile(
            service_account_name, service_account_keyfile, scopes)
        if credentials is not None:
            return credentials
    credentials = GaeAssertionCredentials.Get(scopes)
    if credentials is not None:
        return credentials
    credentials = GceAssertionCredentials.Get(scopes)
    if credentials is not None:
        return credentials
    credentials_filename = credentials_filename or os.path.expanduser(
        '~/.apitools.token')
    credentials = CredentialsFromFile(credentials_filename, client_info)
    if credentials is not None:
        return credentials
    raise exceptions.CredentialsError('Could not create valid credentials')