Python oauth2client.client.HttpAccessTokenRefreshError() Examples

The following are 16 code examples of oauth2client.client.HttpAccessTokenRefreshError(). 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.client , or try the search function .
Example #1
Source File: file_utils.py    From loom with GNU Affero General Public License v3.0 7 votes vote down vote up
def get_bucket(self, bucket_id):
        try:
            if self.retry:
                self.bucket = execute_with_retries(
                    lambda: self.client.get_bucket(bucket_id),
                    (Exception,),
                    logger,
                    'Get bucket',
                    nonretryable_errors=(google.cloud.exceptions.Forbidden,),
                )
            else:
                self.bucket = self.client.get_bucket(bucket_id)
        except HttpAccessTokenRefreshError:
            raise FileUtilsError(
                'Failed to access bucket "%s". Are you logged in? '\
                'Try "gcloud auth login"' % bucket_id) 
Example #2
Source File: gce.py    From alfred-gmail with MIT License 6 votes vote down vote up
def _refresh(self, http_request):
        """Refreshes the access_token.

        Skip all the storage hoops and just refresh using the API.

        Args:
            http_request: callable, a callable that matches the method
                          signature of httplib2.Http.request, used to make
                          the refresh request.

        Raises:
            HttpAccessTokenRefreshError: When the refresh fails.
        """
        try:
            self._retrieve_info(http_request)
            self.access_token, self.token_expiry = _metadata.get_token(
                http_request, service_account=self.service_account_email)
        except httplib2.HttpLib2Error as e:
            raise client.HttpAccessTokenRefreshError(str(e)) 
Example #3
Source File: gce.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def _refresh(self, http):
        """Refreshes the access token.

        Skip all the storage hoops and just refresh using the API.

        Args:
            http: an object to be used to make HTTP requests.

        Raises:
            HttpAccessTokenRefreshError: When the refresh fails.
        """
        try:
            self._retrieve_info(http)
            self.access_token, self.token_expiry = _metadata.get_token(
                http, service_account=self.service_account_email)
        except http_client.HTTPException as err:
            raise client.HttpAccessTokenRefreshError(str(err)) 
Example #4
Source File: gscout.py    From G-Scout with GNU General Public License v3.0 5 votes vote down vote up
def main():
    # configure command line parameters
    parser = argparse.ArgumentParser(description='Google Cloud Platform Security Tool')
    parser.add_argument('--overwrite', action='store_true', help='Overwrite existing output for the same projects')
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('--project-name', '-p-name', help='Project name to scan')
    group.add_argument('--project-id', '-p-id', help='Project id to scan')
    group.add_argument('--organization', '-o', help='Organization id to scan')
    group.add_argument('--folder-id', '-f-id', help='Folder id to scan')
    args = parser.parse_args()

    output_dir = "Report Output"
    if not os.path.isdir(output_dir):
        try:
            os.makedirs(output_dir)
        except Exception as e:
            msg = "could not make output directory '%s'. The error encountered was: %s%s%sStack trace:%s%s" % (output_dir, e, os.linesep, os.linesep, os.linesep, traceback.format_exc())
            print("Error: %s" % (msg))
            logging.exception(msg)
    try:
        if args.project_name :
            list_projects(project_or_org='project-name', specifier=args.project_name)
        elif args.project_id :
            list_projects(project_or_org='project-id', specifier=args.project_id)
        elif args.folder_id :
            list_projects(project_or_org='folder-id', specifier=args.folder_id)
        else:
            list_projects(project_or_org='organization', specifier=args.organization)
    except (HttpAccessTokenRefreshError, ApplicationDefaultCredentialsError):
        from core import config
        list_projects(project_or_org='project' if args.project else 'organization',
                      specifier=args.project if args.project else args.organization)

    for project in db.table("Project").all():
        print("Scouting ", project['projectId'])
        fetch_all(project, args.overwrite) 
Example #5
Source File: gce.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _refresh(self, http_request):
        """Refreshes the access_token.

        Skip all the storage hoops and just refresh using the API.

        Args:
            http_request: callable, a callable that matches the method
                          signature of httplib2.Http.request, used to make
                          the refresh request.

        Raises:
            HttpAccessTokenRefreshError: When the refresh fails.
        """
        response, content = http_request(
            META, headers={'Metadata-Flavor': 'Google'})
        content = _from_bytes(content)
        if response.status == http_client.OK:
            try:
                token_content = json.loads(content)
            except Exception as e:
                raise HttpAccessTokenRefreshError(str(e),
                                                  status=response.status)
            self.access_token = token_content['access_token']
        else:
            if response.status == http_client.NOT_FOUND:
                content += (' This can occur if a VM was created'
                            ' with no service account or scopes.')
            raise HttpAccessTokenRefreshError(content, status=response.status) 
Example #6
Source File: gce.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def _refresh(self, http_request):
        """Refreshes the access_token.

        Skip all the storage hoops and just refresh using the API.

        Args:
            http_request: callable, a callable that matches the method
                          signature of httplib2.Http.request, used to make
                          the refresh request.

        Raises:
            HttpAccessTokenRefreshError: When the refresh fails.
        """
        query = '?scope=%s' % urllib.parse.quote(self.scope, '')
        uri = META.replace('{?scope}', query)
        response, content = http_request(
            uri, headers={'Metadata-Flavor': 'Google'})
        content = _from_bytes(content)
        if response.status == http_client.OK:
            try:
                token_content = json.loads(content)
            except Exception as e:
                raise HttpAccessTokenRefreshError(str(e),
                                                  status=response.status)
            self.access_token = token_content['access_token']
        else:
            if response.status == http_client.NOT_FOUND:
                content += (' This can occur if a VM was created'
                            ' with no service account or scopes.')
            raise HttpAccessTokenRefreshError(content, status=response.status) 
Example #7
Source File: gce.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def _refresh(self, http_request):
        """Refreshes the access_token.

        Skip all the storage hoops and just refresh using the API.

        Args:
            http_request: callable, a callable that matches the method
                          signature of httplib2.Http.request, used to make
                          the refresh request.

        Raises:
            HttpAccessTokenRefreshError: When the refresh fails.
        """
        query = '?scope=%s' % urllib.parse.quote(self.scope, '')
        uri = META.replace('{?scope}', query)
        response, content = http_request(
            uri, headers={'Metadata-Flavor': 'Google'})
        content = _from_bytes(content)
        if response.status == http_client.OK:
            try:
                token_content = json.loads(content)
            except Exception as e:
                raise HttpAccessTokenRefreshError(str(e),
                                                  status=response.status)
            self.access_token = token_content['access_token']
        else:
            if response.status == http_client.NOT_FOUND:
                content += (' This can occur if a VM was created'
                            ' with no service account or scopes.')
            raise HttpAccessTokenRefreshError(content, status=response.status) 
Example #8
Source File: gce.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def _refresh(self, http_request):
        """Refreshes the access_token.

        Skip all the storage hoops and just refresh using the API.

        Args:
            http_request: callable, a callable that matches the method
                          signature of httplib2.Http.request, used to make
                          the refresh request.

        Raises:
            HttpAccessTokenRefreshError: When the refresh fails.
        """
        query = '?scope=%s' % urllib.parse.quote(self.scope, '')
        uri = META.replace('{?scope}', query)
        response, content = http_request(
            uri, headers={'Metadata-Flavor': 'Google'})
        content = _from_bytes(content)
        if response.status == http_client.OK:
            try:
                token_content = json.loads(content)
            except Exception as e:
                raise HttpAccessTokenRefreshError(str(e),
                                                  status=response.status)
            self.access_token = token_content['access_token']
        else:
            if response.status == http_client.NOT_FOUND:
                content += (' This can occur if a VM was created'
                            ' with no service account or scopes.')
            raise HttpAccessTokenRefreshError(content, status=response.status) 
Example #9
Source File: gce.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def _refresh(self, http_request):
        """Refreshes the access_token.

        Skip all the storage hoops and just refresh using the API.

        Args:
            http_request: callable, a callable that matches the method
                          signature of httplib2.Http.request, used to make
                          the refresh request.

        Raises:
            HttpAccessTokenRefreshError: When the refresh fails.
        """
        query = '?scope=%s' % urllib.parse.quote(self.scope, '')
        uri = META.replace('{?scope}', query)
        response, content = http_request(
            uri, headers={'Metadata-Flavor': 'Google'})
        content = _from_bytes(content)
        if response.status == http_client.OK:
            try:
                token_content = json.loads(content)
            except Exception as e:
                raise HttpAccessTokenRefreshError(str(e),
                                                  status=response.status)
            self.access_token = token_content['access_token']
        else:
            if response.status == http_client.NOT_FOUND:
                content += (' This can occur if a VM was created'
                            ' with no service account or scopes.')
            raise HttpAccessTokenRefreshError(content, status=response.status) 
Example #10
Source File: gce.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def _refresh(self, http_request):
        """Refreshes the access_token.

        Skip all the storage hoops and just refresh using the API.

        Args:
            http_request: callable, a callable that matches the method
                          signature of httplib2.Http.request, used to make
                          the refresh request.

        Raises:
            HttpAccessTokenRefreshError: When the refresh fails.
        """
        query = '?scope=%s' % urllib.parse.quote(self.scope, '')
        uri = META.replace('{?scope}', query)
        response, content = http_request(
            uri, headers={'Metadata-Flavor': 'Google'})
        content = _from_bytes(content)
        if response.status == http_client.OK:
            try:
                token_content = json.loads(content)
            except Exception as e:
                raise HttpAccessTokenRefreshError(str(e),
                                                  status=response.status)
            self.access_token = token_content['access_token']
        else:
            if response.status == http_client.NOT_FOUND:
                content += (' This can occur if a VM was created'
                            ' with no service account or scopes.')
            raise HttpAccessTokenRefreshError(content, status=response.status) 
Example #11
Source File: http_wrapper_test.py    From apitools with Apache License 2.0 5 votes vote down vote up
def testExceptionHandlerHttpAccessTokenError(self):
        exception_arg = HttpAccessTokenRefreshError(status=503)
        retry_args = http_wrapper.ExceptionRetryArgs(
            http={'connections': {}}, http_request=_MockHttpRequest(),
            exc=exception_arg, num_retries=0, max_retry_wait=0,
            total_wait_sec=0)

        # Disable time.sleep for this handler as it is called with
        # a minimum value of 1 second.
        with patch('time.sleep', return_value=None):
            http_wrapper.HandleExceptionsAndRebuildHttpConnections(
                retry_args) 
Example #12
Source File: http_wrapper_test.py    From apitools with Apache License 2.0 5 votes vote down vote up
def testExceptionHandlerHttpAccessTokenErrorRaises(self):
        exception_arg = HttpAccessTokenRefreshError(status=200)
        retry_args = http_wrapper.ExceptionRetryArgs(
            http={'connections': {}}, http_request=_MockHttpRequest(),
            exc=exception_arg, num_retries=0, max_retry_wait=0,
            total_wait_sec=0)

        # Disable time.sleep for this handler as it is called with
        # a minimum value of 1 second.
        with self.assertRaises(HttpAccessTokenRefreshError):
            with patch('time.sleep', return_value=None):
                http_wrapper.HandleExceptionsAndRebuildHttpConnections(
                    retry_args) 
Example #13
Source File: conftest.py    From getting-started-python with Apache License 2.0 5 votes vote down vote up
def flaky_filter(info, *args):
    """Used by flaky to determine when to re-run a test case."""
    _, e, _ = info
    return isinstance(e, (ServiceUnavailable, HttpAccessTokenRefreshError)) 
Example #14
Source File: gce.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def _refresh(self, http_request):
        """Refreshes the access_token.

        Skip all the storage hoops and just refresh using the API.

        Args:
            http_request: callable, a callable that matches the method
                          signature of httplib2.Http.request, used to make
                          the refresh request.

        Raises:
            HttpAccessTokenRefreshError: When the refresh fails.
        """
        query = '?scope=%s' % urllib.parse.quote(self.scope, '')
        uri = META.replace('{?scope}', query)
        response, content = http_request(uri)
        content = _from_bytes(content)
        if response.status == 200:
            try:
                d = json.loads(content)
            except Exception as e:
                raise HttpAccessTokenRefreshError(str(e),
                                                  status=response.status)
            self.access_token = d['accessToken']
        else:
            if response.status == 404:
                content += (' This can occur if a VM was created'
                            ' with no service account or scopes.')
            raise HttpAccessTokenRefreshError(content, status=response.status) 
Example #15
Source File: gce.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def _refresh(self, http_request):
        """Refreshes the access_token.

        Skip all the storage hoops and just refresh using the API.

        Args:
            http_request: callable, a callable that matches the method
                          signature of httplib2.Http.request, used to make
                          the refresh request.

        Raises:
            HttpAccessTokenRefreshError: When the refresh fails.
        """
        query = '?scope=%s' % urllib.parse.quote(self.scope, '')
        uri = META.replace('{?scope}', query)
        response, content = http_request(uri)
        content = _from_bytes(content)
        if response.status == 200:
            try:
                d = json.loads(content)
            except Exception as e:
                raise HttpAccessTokenRefreshError(str(e),
                                                  status=response.status)
            self.access_token = d['accessToken']
        else:
            if response.status == 404:
                content += (' This can occur if a VM was created'
                            ' with no service account or scopes.')
            raise HttpAccessTokenRefreshError(content, status=response.status) 
Example #16
Source File: cleaner.py    From google-drive-trash-cleaner with GNU General Public License v3.0 4 votes vote down vote up
def main():
    flags = parse_cmdline()
    logger = configure_logs(flags.logfile)
    pageTokenFile = PageTokenFile(flags.ptokenfile)
    for i in range(RETRY_NUM):
        try:
            service = build_service(flags)
            pageToken = pageTokenFile.get()
            deletionList, pageTokenBefore, pageTokenAfter = \
                get_deletion_list(service, pageToken, flags)
            pageTokenFile.save(pageTokenBefore)
            listEmpty = delete_old_files(service, deletionList, flags)
        except client.HttpAccessTokenRefreshError:
            print('Authentication error')
        except httplib2.ServerNotFoundError as e:
            print('Error:', e)
        except TimeoutError:
            print('Timeout: Google backend error.')
            print('Retries unsuccessful. Abort action.')
            return
        else:
            break
        time.sleep(RETRY_INTERVAL)
    else:
        print("Retries unsuccessful. Abort action.")
        return
    
    if listEmpty:
        pageTokenFile.save(pageTokenAfter)