示例#1
0
    def __init__(self, access_info: dict, queue: beanstalk.Connection) -> None:
        """initialize our google drive object
        with the device oAuth2 info"""
        self.post_status(
            'GoogleDrive.__init__(): access_info is type {0}'.format(
                type(access_info)))
        try:
            self.queue = queue
            if self.queue:
                self.queue.use(STATUS_QUEUE)

            access_token = access_info['access_token']
            refresh_token = access_info['refresh_token']
            expires_in = access_info['expires_in']
            token_type = access_info[
                'token_type']  #pylint:disable-msg=unused-variable

            credentials = client.GoogleCredentials(
                access_token=access_token,
                client_id=google_api.CLIENT_ID,
                client_secret=google_api.CLIENT_SECRET,
                refresh_token=refresh_token,
                token_expiry=expires_in,
                token_uri="https://www.googleapis.com/oauth2/v4/token",
                user_agent='my-user-agent/1.0')

            google_http = credentials.authorize(Http())
            google_drive = discovery.build('drive', 'v3', http=google_http)
            self.drive_client = google_drive.files()  # pylint: disable=E1101
        except KeyError as key_error:
            self.post_status("Error with access info: {0}".format(
                key_error.__str__()))
示例#2
0
    def __init__(self, access_token, refresh_token, client_secret, client_id,
                 **kwargs):
        credentials = client.GoogleCredentials(
            access_token,
            client_id=client_id,
            client_secret=client_secret,
            refresh_token=refresh_token,
            token_expiry=None,
            token_uri=GOOGLE_TOKEN_URI,
            user_agent=None,
            revoke_uri=GOOGLE_REVOKE_URI,
        )

        http = credentials.authorize(httplib2.Http())
        credentials.refresh(http)

        self._client = discovery.build(self.API_NAME,
                                       self.API_VERSION,
                                       http=http,
                                       cache_discovery=False)

        self.kwargs = kwargs

        check_date_range_definition_conformity(self.kwargs.get("start_date"),
                                               self.kwargs.get("end_date"),
                                               self.kwargs.get("day_range"))
示例#3
0
    def __init__(self, access_token, refresh_token, client_id, client_secret,
                 **kwargs):
        credentials = client.GoogleCredentials(
            access_token=access_token,
            client_id=client_id,
            client_secret=client_secret,
            refresh_token=refresh_token,
            token_expiry=None,
            token_uri=GOOGLE_TOKEN_URI,
            user_agent=None,
            revoke_uri=GOOGLE_REVOKE_URI,
        )

        http = credentials.authorize(httplib2.Http())
        credentials.refresh(http)
        self.client_v4 = discovery.build("analytics",
                                         "v4",
                                         http=http,
                                         cache_discovery=False,
                                         discoveryServiceUrl=DISCOVERY_URI)
        self.client_v3 = discovery.build("analytics", "v3", http=http)
        self.kwargs = kwargs
        self.kwargs["credentials"] = credentials
        self.views_metadata = {}
        self.view_ids = self.kwargs.get("view_id")
        self.date_range = self.get_date_range_for_ga_request()
        self.sampling_level = self.kwargs.get("sampling_level")
        self.add_view = self.kwargs.get("add_view", False)
    def getGoogleCredentials(app, user):

        tokenExpiry = utils.stringToDatetime(user.googleTokenExpiry)

        googlecredentials = client.GoogleCredentials(
            client_id=app.config["GOOGLE_CLIENT_ID"],
            client_secret=app.config["GOOGLE_CLIENT_SECRET"],
            access_token=user.googleAccessToken,
            refresh_token=user.googleRefreshToken,
            token_expiry=tokenExpiry,
            token_uri=user.googleTokenURI,
            revoke_uri=user.googleRevokeURI,
            user_agent=None)

        if googlecredentials.access_token_expired:
            app.logger.debug(
                "Google credentials for %s expired. Asking for new token",
                user.email)
            http = httplib2.Http()
            googlecredentials.refresh(http)
            user.googleAccessToken = googlecredentials.access_token
            user.googleTokenExpiry = utils.datetimeToString(
                googlecredentials.token_expiry)
            user.save()

        return googlecredentials
def SaveCredentialsAsADC(creds):
    """Saves the credentials to the given file.

  Args:
    creds: The credentials obtained from a web flow.

  Returns:
    str, The full path to the ADC file that was written.
  """
    google_creds = client.GoogleCredentials(
        creds.access_token, creds.client_id, creds.client_secret,
        creds.refresh_token, creds.token_expiry, creds.token_uri,
        creds.user_agent, creds.revoke_uri)
    adc_file = ADCFilePath()
    try:
        with files.OpenForWritingPrivate(adc_file) as f:
            json.dump(google_creds.serialization_data,
                      f,
                      sort_keys=True,
                      indent=2,
                      separators=(',', ': '))
    except IOError as e:
        log.debug(e, exc_info=True)
        raise CredentialFileSaveError(
            'Error saving Application Default Credentials: ' + str(e))
    return os.path.abspath(adc_file)
示例#6
0
def SaveCredentialsAsADC(creds, file_path):
    """Saves the credentials to the given file.

  Args:
    creds: client.OAuth2Credentials, obtained from a web flow
        or service account.
    file_path: str, file path to store credentials to. The file will be created.


  Raises:
    CredentialFileSaveError, on file io errors.
  """
    google_creds = client.GoogleCredentials(
        creds.access_token, creds.client_id, creds.client_secret,
        creds.refresh_token, creds.token_expiry, creds.token_uri,
        creds.user_agent, creds.revoke_uri)
    try:
        with files.OpenForWritingPrivate(file_path) as f:
            json.dump(google_creds.serialization_data,
                      f,
                      sort_keys=True,
                      indent=2,
                      separators=(',', ': '))
    except IOError as e:
        log.debug(e, exc_info=True)
        raise CredentialFileSaveError(
            'Error saving Application Default Credentials: ' + str(e))
示例#7
0
  def LoginAs(self, account, creds, project, activate, brief):
    """Logs in with valid credentials."""
    if not activate:
      return creds
    properties.PersistProperty(properties.VALUES.core.account, account)
    if project:
      properties.PersistProperty(properties.VALUES.core.project, project)

    google_creds = client.GoogleCredentials(
        creds.access_token, creds.client_id, creds.client_secret,
        creds.refresh_token, creds.token_expiry, creds.token_uri,
        creds.user_agent, creds.revoke_uri)
    try:
      auth_util.CreateWellKnownFileDir()
      client.save_to_well_known_file(google_creds)
    except IOError as e:
      raise c_exc.ToolException(
          'error saving Application Default Credentials: ' + str(e))
    if not brief:
      log.status.write('Saved Application Default Credentials.\n')
      log.warning(
          '`gcloud auth login` will stop writing application default '
          'credentials\nin a future release. See:\n    '
          'https://developers.google.com/identity/protocols/'
          'application-default-credentials#toolcloudsdk'
          '\nfor more information.')

    if not brief:
      log.status.write(
          '\nYou are now logged in as [{account}].\n'
          'Your current project is [{project}].  You can change this setting '
          'by running:\n  $ gcloud config set project PROJECT_ID\n'.format(
              account=account, project=properties.VALUES.core.project.Get()))
    return creds
def createAnalyticsReport():

    #The real code that initalized the client
    credentials = client.GoogleCredentials(access_token=ACCESS_TOKEN,
                                           refresh_token=REFRESH_TOKEN,
                                           client_id=CLIENT_ID,
                                           client_secret=CLIENT_SECRET,
                                           token_uri=TOKEN_URI,
                                           token_expiry=TOKEN_EXPIRY,
                                           user_agent=USER_AGENT)
    #Initialize Http Protocol
    http = lib2.Http()

    #Authorize client
    authorized = credentials.authorize(http)

    #API Name and Verison, these don't change until
    #they release a new API version for us to play with.
    api_name = 'analyticsreporting'
    api_version = 'v4'

    #Let's build the client
    analytics = google_build(serviceName=api_name,
                             version=api_version,
                             http=authorized)
    return analytics
示例#9
0
 def LoginAs(self, account, creds, project, activate, brief):
   """Logs in with valid credentials."""
   if not activate:
     return creds
   properties.PersistProperty(properties.VALUES.core.account, account)
   if project:
     properties.PersistProperty(properties.VALUES.core.project, project)
   if not config.Paths().workspace_dir:
     google_creds = client.GoogleCredentials(
         creds.access_token, creds.client_id, creds.client_secret,
         creds.refresh_token, creds.token_expiry, creds.token_uri,
         creds.user_agent, creds.revoke_uri)
     try:
       client.save_to_well_known_file(google_creds)
     except IOError as e:
       raise c_exc.ToolException(
           'error saving Application Default Credentials: ' + str(e))
     if not brief:
       log.status.write('Saved Application Default Credentials.\n')
   if not brief:
     log.status.write(
         '\nYou are now logged in as [{account}].\n'
         'Your current project is [{project}].  You can change this setting '
         'by running:\n  $ gcloud config set project PROJECT_ID\n'.format(
             account=account, project=properties.VALUES.core.project.Get()))
   return creds
 def test_google_call_credentials(self):
     creds = oauth2client_client.GoogleCredentials(
         'token', 'client_id', 'secret', 'refresh_token',
         datetime.datetime(2008, 6, 24), 'https://refresh.uri.com/',
         'user_agent')
     call_creds = implementations.google_call_credentials(creds)
     self.assertIsInstance(call_creds, implementations.CallCredentials)
def google_calendar_raw_connection(oauth2_clinet_id, oauth2_secrete, sender_id,
                                   change, org_credentials):
    """
    This method used for connect with google calendar api.
    """
    if not org_credentials:
        error_message = 'This sender {sender_id} don\'t have oauth2 access-token, yet. Please send this link {register_link} to the sender. So he can register with his google account, again.'.format(
            sender_id=sender_id, register_link=settings.REGISTER_URL)
        logging.error(error_message)
        return None
    else:
        json_credentials = json.loads(org_credentials)
        credentials = client.GoogleCredentials(
            None, json_credentials['client_id'],
            json_credentials['client_secret'],
            json_credentials['refresh_token'],
            json_credentials['token_expiry'],
            "https://accounts.google.com/o/oauth2/token", None)

    # Create an httplib2.Http object to handle our HTTP requests and authorize it
    # with our good Credentials.
    http = httplib2shim.Http()
    http = credentials.authorize(http)
    service = discovery.build('calendar', 'v3', http=http)

    return {'http': http, 'service': service}
示例#12
0
def upload_gdrive(file_src,
                  file_dest,
                  client_id,
                  client_secret,
                  refresh_token,
                  folder=None):
    import httplib2
    import os
    from apiclient import discovery
    from oauth2client import client
    from apiclient.http import MediaFileUpload

    credentials = client.GoogleCredentials(
        None, client_id, client_secret, refresh_token, None,
        "https://accounts.google.com/o/oauth2/token", 'scanner-ocr')

    http = credentials.authorize(httplib2.Http())
    service = discovery.build('drive', 'v3', http=http, cache_discovery=False)

    file_metadata = {
        'name': file_dest,
    }
    if folder is not None:
        file_metadata['parents'] = [folder]

    media = MediaFileUpload(file_src, mimetype='application/pdf')
    file = service.files().create(body=file_metadata,
                                  media_body=media,
                                  fields='id').execute()
示例#13
0
def FromJson(json_value):
    """Returns Oauth2client credentials from library independend json format."""
    json_key = json.loads(json_value)
    cred_type = CredentialType.FromTypeKey(json_key['type'])
    if cred_type == CredentialType.SERVICE_ACCOUNT:
        cred = service_account.ServiceAccountCredentials.from_json_keyfile_dict(
            json_key, scopes=config.CLOUDSDK_SCOPES)
        cred.user_agent = cred._user_agent = config.CLOUDSDK_USER_AGENT
    elif cred_type == CredentialType.USER_ACCOUNT:
        cred = client.GoogleCredentials(
            access_token=None,
            client_id=json_key['client_id'],
            client_secret=json_key['client_secret'],
            refresh_token=json_key['refresh_token'],
            token_expiry=None,
            token_uri=oauth2client.GOOGLE_TOKEN_URI,
            user_agent=config.CLOUDSDK_USER_AGENT)
    elif cred_type == CredentialType.P12_SERVICE_ACCOUNT:
        # pylint: disable=protected-access
        cred = service_account.ServiceAccountCredentials._from_p12_keyfile_contents(
            service_account_email=json_key['client_email'],
            private_key_pkcs12=base64.b64decode(json_key['private_key']),
            private_key_password=json_key['password'],
            scopes=config.CLOUDSDK_SCOPES)
        cred.user_agent = cred._user_agent = config.CLOUDSDK_USER_AGENT
    else:
        raise UnknownCredentialsType(json_key['type'])
    return cred
示例#14
0
def get_credentials():
    client_id = os.environ['GMAIL_CLIENT_ID']
    client_secret = os.environ['GMAIL_CLIENT_SECRET']
    refresh_token = os.environ['GMAIL_REFRESH_TOKEN']

    credentials = client.GoogleCredentials(
        None, client_id, client_secret, refresh_token, None,
        "https://accounts.google.com/o/oauth2/token", 'my-user-agent')
    return credentials
示例#15
0
def auth_credentials():
    credentials = oauth_client.GoogleCredentials(
        access_token=current_user.google_access_token,
        refresh_token=current_user.google_refresh_token,
        client_id=Auth.CLIENT_ID,
        client_secret=Auth.CLIENT_SECRET,
        token_uri='https://accounts.google.com/o/oauth2/token',
        token_expiry=(datetime.now() + timedelta(days=10)),
        user_agent='Melytix-user-agent/1.0')
    # authorizing credentials (if token is expired it will refresh it)
    authorized = credentials.authorize(lib2.Http())
    return authorized
示例#16
0
 def get_credentials(self):
     isoFormat = "%Y-%m-%dT%H:%M:%S.%f"
     access_token = self.token['access_token']
     refresh_token = self.token['refresh_token']
     expires_at = datetime.strptime(self.token['expires_at'], isoFormat)
     token_uri = 'https://accounts.google.com/o/oauth2/token'
     user_agent = 'gaugette/1.0'
     credentials = client.GoogleCredentials(access_token, self.client_id,
                                            self.client_secret,
                                            refresh_token, expires_at,
                                            token_uri, user_agent)
     return credentials
示例#17
0
 def __build_service(self):
     id,secret,token = self.__get_creds()
     client_credentials =  client.GoogleCredentials(
         None,
         id,
         secret,
         token,
         None,
         "https://accounts.google.com/o/oauth2/token",
         'my-user-agent'
     )
     http = client_credentials.authorize(httplib2.Http())
     return build('gmail', 'v1', http=http, cache_discovery=False)
示例#18
0
 def __init__(self):
     self.uil = QUiLoader()
     self.loadSettings()
     self.clientID, self.clientSecret = '417133363442-dtm48svvid8ntj6locavdvdt3e982n6k.apps.googleusercontent.com', 'UmzBQInps-09e6VNbnsRT0BG'
     if self.accessToken and self.refreshToken:
         credentials = client.GoogleCredentials(
             self.accessToken, self.clientID, self.clientSecret,
             self.refreshToken, None,
             "https://accounts.google.com/o/oauth2/token",
             'ScreenCloudGoogleDrivePlugin/1.3')
         self.driveService = build('drive',
                                   'v3',
                                   http=credentials.authorize(Http()))
示例#19
0
def _ConvertCredentialsToADC(credentials):
    """Converts given credentials to application default credentials."""
    creds_type = CredentialType.FromCredentials(credentials)
    if creds_type == CredentialType.P12_SERVICE_ACCOUNT:
        raise CredentialFileSaveError(
            'Error saving Application Default Credentials: p12 keys are not'
            'supported in this format')
    if creds_type == CredentialType.USER_ACCOUNT:
        credentials = client.GoogleCredentials(
            credentials.access_token, credentials.client_id,
            credentials.client_secret, credentials.refresh_token,
            credentials.token_expiry, credentials.token_uri,
            credentials.user_agent, credentials.revoke_uri)
    return credentials.serialization_data
示例#20
0
def _ConvertOauth2ClientCredentialsToADC(credentials):
    """Converts an oauth2client credentials to application default credentials."""
    creds_type = CredentialType.FromCredentials(credentials)
    if creds_type not in (CredentialType.USER_ACCOUNT,
                          CredentialType.SERVICE_ACCOUNT):
        raise ADCError('Cannot convert credentials of type {} to application '
                       'default credentials.'.format(type(credentials)))
    if creds_type == CredentialType.USER_ACCOUNT:
        credentials = client.GoogleCredentials(
            credentials.access_token, credentials.client_id,
            credentials.client_secret, credentials.refresh_token,
            credentials.token_expiry, credentials.token_uri,
            credentials.user_agent, credentials.revoke_uri)
    return credentials.serialization_data
示例#21
0
def run_user_json():
    with open(USER_KEY_PATH, 'r') as file_object:
        client_credentials = json.load(file_object)

    credentials = client.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',
    )

    _check_user_info(credentials, USER_KEY_EMAIL)
示例#22
0
def getGoogleCredentials(app, user):

    tokenExpiry = stringToDatetime(user.googleTokenExpiry)

    googlecredentials = client.GoogleCredentials(
        client_id=app.config["GOOGLE_CLIENT_ID"],
        client_secret=app.config["GOOGLE_CLIENT_SECRET"],
        access_token=user.googleAccessToken,
        refresh_token=user.googleRefreshToken,
        token_expiry=tokenExpiry,
        token_uri=user.googleTokenURI,
        revoke_uri=user.googleRevokeURI,
        user_agent=None)

    return googlecredentials
示例#23
0
def get_google_http_auth_n_user_timezone(username):
    with open(backend.client_secret_file) as f:
        client_secret_json = json.load(f)
        client_id = client_secret_json['web']['client_id']
        client_secret = client_secret_json['web']['client_secret']
    ds = datastore.Client()
    key = ds.key('credentials', username)
    user = ds.get(key)
    assert user.key.id_or_name == username
    refresh_token = user['refresh_token']
    timezone = user['timezone']
    creds = client.GoogleCredentials(
        None, client_id, client_secret, refresh_token, None,
        "https://accounts.google.com/o/oauth2/token", "Python")
    http_auth = creds.authorize(httplib2.Http())
    return http_auth, timezone
 def __init__(self, access_token, client_id, client_secret, refresh_token):
     self._credentials = client.GoogleCredentials(
         access_token=access_token,
         client_id=client_id,
         client_secret=client_secret,
         refresh_token=refresh_token,
         token_expiry=None,
         token_uri=GOOGLE_TOKEN_URI,
         user_agent=None,
     )
     http = self._credentials.authorize(httplib2.Http())
     self._credentials.refresh(http)
     self.auth = (
         f"{self._credentials.token_response['token_type']} {self._credentials.token_response['access_token']}"
     )
     self._service = discovery.build(self.API_NAME, self.API_VERSION, http=http, cache_discovery=False)
示例#25
0
def birthday_today():
    """
    return list of strings of name (and birthyear) of people in
    my contacts list which have birthday today.
    """

    # because access token expires in 3600 seconds (which is 1 hour), we also need
    # to provide the refresh token and refresh token expiry, see
    # https://stackoverflow.com/a/37418906/119861
    client_id = os.environ['GOOGLE_PEOPLE_CLIENT_ID']
    client_secret = os.environ['GOOGLE_PEOPLE_CLIENT_SECRET']
    refresh_token = os.environ['GOOGLE_PEOPLE_REFRESH_TOKEN']
    credentials = client.GoogleCredentials(
        None, client_id, client_secret, refresh_token, None,
        "https://accounts.google.com/o/oauth2/token", 'sms-proxy')

    # credentials = client.AccessTokenCredentials(access_token, 'sms-proxy')
    http = credentials.authorize(httplib2.Http())
    service = discovery.build(
        'people',
        'v1',
        http=http,
        discoveryServiceUrl='https://people.googleapis.com/$discovery/rest',
        cache_discovery=False)

    results = service.people().connections().list(
        resourceName='people/me',
        pageSize=2000,
        personFields='names,birthdays').execute()
    connections = results.get('connections', [])
    today = datetime.date.today()
    res = []

    for person in connections:
        if 'birthdays' in person and 'names' in person and len(
                person['names']) > 0:
            birthday = person['birthdays'][0]['date']
            name = person['names'][0]['displayName']
            if birthday[
                    'month'] == today.month:  # and birthday['day'] == today.day:
                if 'year' in birthday:
                    res.append("{}: {}".format(name, birthday['year']))
                else:
                    res.append("{}".format(name))
    return res
示例#26
0
def get_google_service():
    refresh_token = config["GOOGLE_AUTH"]["refresh_token"]
    client_id = config["GOOGLE_AUTH"]["client_id"]
    client_secret = config["GOOGLE_AUTH"]["client_secret"]
    token_uri = config["GOOGLE_AUTH"]["token_uri"]
    token_expiry = int(config["GOOGLE_AUTH"]["token_expiry"])
    api_name = config["GOOGLE_AUTH"]["api_name"]
    api_version = config["GOOGLE_AUTH"]["api_version"]

    credentials = client.GoogleCredentials(access_token=None,
                                           refresh_token=refresh_token,
                                           client_id=client_id,
                                           client_secret=client_secret,
                                           token_uri=token_uri,
                                           token_expiry=token_expiry,
                                           user_agent=None)

    service = build(api_name, api_version, credentials=credentials)
    return service
 def SaveCredentials(self, creds, brief):
     """Saves the credentials in the well-known file for ADC."""
     google_creds = client.GoogleCredentials(
         creds.access_token, creds.client_id, creds.client_secret,
         creds.refresh_token, creds.token_expiry, creds.token_uri,
         creds.user_agent, creds.revoke_uri)
     try:
         client.save_to_well_known_file(google_creds)
     except IOError as e:
         raise c_exc.ToolException(
             'error saving Application Default Credentials: ' + str(e))
     if not brief:
         log.status.write(
             '\nApplication Default Credentials are now saved, and will\n'
             'use the provided account.\n')
         log.status.write(
             '\nThis does not affect any credentials that you may have\n'
             'set up for the Google Cloud SDK.\n')
     return creds
示例#28
0
def refresh_token(username):
    SCOPES = [
        'https://www.googleapis.com/auth/calendar.readonly',
        'https://www.googleapis.com/auth/tasks.readonly'
    ]
    creds = None
    client_id = '828422134130-bneqqft7mngj1be10i0j2ath0tl2hc9i.apps.googleusercontent.com'
    client_secret = 'ozBOZnvxR8vkoSOnh11kql0h'
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    user_creds, created = UserCredentials.objects.get_or_create(
        user__username=username)
    credentials = user_creds.credentials
    if credentials:
        with open(credentials, 'rb') as token:
            creds = pickle.load(token)
    else:
        credentials = os.path.join(
            BASE_DIR,
            'tokens/{}_token.pickle'.format(user_creds.user.username))
        user_creds.credentials = credentials
        user_creds.save()
    # If there are no (valid) credentials available, let the user log in.
    if not creds:
        if creds and creds.expired and creds.refresh_token:
            creds = client.GoogleCredentials(
                None, client_id, client_secret, creds.refresh_token,
                creds.expiry, "https://accounts.google.com/o/oauth2/token",
                "Smart Mirror")
            http = creds.authorize(httplib2.Http())
            creds.refresh(http)
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'C:/Users/asus/PycharmProjects/Smart_Mirror/smir/client_secret.json',
                SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open(credentials, 'wb') as token:
            pickle.dump(creds, token)
    return creds
示例#29
0
def SaveCredentialsAsADC(credentials, file_path):
  """Saves the credentials to the given file.

  This file can be read back via
    cred = client.GoogleCredentials.from_stream(file_path)

  Args:
    credentials: client.OAuth2Credentials, obtained from a web flow
        or service account.
    file_path: str, file path to store credentials to. The file will be created.

  Raises:
    CredentialFileSaveError: on file io errors.
  """
  creds_type = creds.CredentialType.FromCredentials(credentials)
  if creds_type == creds.CredentialType.P12_SERVICE_ACCOUNT:
    raise CredentialFileSaveError(
        'Error saving Application Default Credentials: p12 keys are not'
        'supported in this format')

  if creds_type == creds.CredentialType.USER_ACCOUNT:
    credentials = client.GoogleCredentials(
        credentials.access_token,
        credentials.client_id,
        credentials.client_secret,
        credentials.refresh_token,
        credentials.token_expiry,
        credentials.token_uri,
        credentials.user_agent,
        credentials.revoke_uri)
  try:
    with files.OpenForWritingPrivate(file_path) as f:
      json.dump(credentials.serialization_data, f, sort_keys=True,
                indent=2, separators=(',', ': '))
  except IOError as e:
    log.debug(e, exc_info=True)
    raise CredentialFileSaveError(
        'Error saving Application Default Credentials: ' + str(e))
    def __init__(self, access_token: str, refresh_token: str, client_id: str,
                 client_secret: str, **kwargs):

        credentials = client.GoogleCredentials(
            access_token,
            client_id=client_id,
            client_secret=client_secret,
            refresh_token=refresh_token,
            token_expiry=None,
            token_uri="https://www.googleapis.com/oauth2/v4/token",
            user_agent=None,
            revoke_uri=GOOGLE_REVOKE_URI,
        )
        http = credentials.authorize(httplib2.Http())
        credentials.refresh(http)

        self._client = discovery.build(self.API_NAME,
                                       self.API_VERSION,
                                       http=http,
                                       cache_discovery=False)

        self.kwargs = kwargs
        self.file_names = self.__get_file_names()