Python oauth2client 模块,client() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用oauth2client.client()

项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def getGDataOAuthToken(gdataObj, credentials=None):
  if not credentials:
    credentials = getClientCredentials(API.FAM2_SCOPES)
  try:
    credentials.refresh(httplib2.Http(disable_ssl_certificate_validation=GC.Values[GC.NO_VERIFY_SSL]))
  except httplib2.ServerNotFoundError as e:
    systemErrorExit(NETWORK_ERROR_RC, str(e))
  except oauth2client.client.AccessTokenRefreshError as e:
    return handleOAuthTokenError(str(e), False)
  gdataObj.additional_headers[u'Authorization'] = u'Bearer {0}'.format(credentials.access_token)
  if not GC.Values[GC.DOMAIN]:
    GC.Values[GC.DOMAIN] = credentials.id_token.get(u'hd', u'UNKNOWN').lower()
  if not GC.Values[GC.CUSTOMER_ID]:
    GC.Values[GC.CUSTOMER_ID] = GC.MY_CUSTOMER
  GM.Globals[GM.ADMIN] = credentials.id_token.get(u'email', u'UNKNOWN').lower()
  GM.Globals[GM.OAUTH2_CLIENT_ID] = credentials.client_id
  gdataObj.domain = GC.Values[GC.DOMAIN]
  gdataObj.source = GAM_INFO
  return True
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def buildGAPIObject(api):
  GM.Globals[GM.CURRENT_API_USER] = None
  _, httpObj, service, cred_family = getAPIversionHttpService(api)
  credentials = getClientCredentials(cred_family)
  try:
    API_Scopes = set(list(service._rootDesc[u'auth'][u'oauth2'][u'scopes']))
  except KeyError:
    API_Scopes = set(API.VAULT_SCOPES) if api == API.VAULT else set()
  GM.Globals[GM.CURRENT_API_SCOPES] = list(API_Scopes.intersection(credentials.scopes))
  if not GM.Globals[GM.CURRENT_API_SCOPES]:
    systemErrorExit(NO_SCOPES_FOR_API_RC, Msg.NO_SCOPES_FOR_API.format(service._rootDesc[u'title']))
  try:
    service._http = credentials.authorize(httpObj)
  except httplib2.ServerNotFoundError as e:
    systemErrorExit(NETWORK_ERROR_RC, str(e))
  except oauth2client.client.AccessTokenRefreshError as e:
    return handleOAuthTokenError(str(e), False)
  if not GC.Values[GC.DOMAIN]:
    GC.Values[GC.DOMAIN] = credentials.id_token.get(u'hd', u'UNKNOWN').lower()
  if not GC.Values[GC.CUSTOMER_ID]:
    GC.Values[GC.CUSTOMER_ID] = GC.MY_CUSTOMER
  GM.Globals[GM.ADMIN] = credentials.id_token.get(u'email', u'UNKNOWN').lower()
  GM.Globals[GM.OAUTH2_CLIENT_ID] = credentials.client_id
  return service
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def doVersion(checkForArgs=True):
  forceCheck = simple = False
  if checkForArgs:
    while Cmd.ArgumentsRemaining():
      myarg = getArgument()
      if myarg == u'check':
        forceCheck = True
      elif myarg == u'simple':
        simple = True
      else:
        unknownArgumentExit()
  if simple:
    writeStdout(__version__)
    return
  import struct
  version_data = u'GAM {0} - {1}\n{2}\nPython {3}.{4}.{5} {6}-bit {7}\ngoogle-api-python-client {8}\noauth2client {9}\n{10} {11}\nPath: {12}\n'
  writeStdout(version_data.format(__version__, GAM_URL, __author__, sys.version_info[0],
                                  sys.version_info[1], sys.version_info[2], struct.calcsize(u'P')*8,
                                  sys.version_info[3], googleapiclient.__version__, oauth2client.__version__, platform.platform(),
                                  platform.machine(), GM.Globals[GM.GAM_PATH]))
  if forceCheck:
    doGAMCheckForUpdates(forceCheck=True)

# gam help
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def getCRMService(login_hint):
  from oauth2client.contrib.dictionary_storage import DictionaryStorage
  scope = u'https://www.googleapis.com/auth/cloud-platform'
  client_id = u'297408095146-fug707qsjv4ikron0hugpevbrjhkmsk7.apps.googleusercontent.com'
  client_secret = u'qM3dP8f_4qedwzWQE1VR4zzU'
  flow = oauth2client.client.OAuth2WebServerFlow(client_id=client_id,
                                                 client_secret=client_secret, scope=scope, redirect_uri=oauth2client.client.OOB_CALLBACK_URN,
                                                 user_agent=GAM_INFO, access_type=u'online', response_type=u'code', login_hint=login_hint)
  storage_dict = {}
  storage = DictionaryStorage(storage_dict, u'credentials')
  flags = cmd_flags(noLocalWebserver=GC.Values[GC.NO_BROWSER])
  httpObj = httplib2.Http(disable_ssl_certificate_validation=GC.Values[GC.NO_VERIFY_SSL])
  try:
    credentials = oauth2client.tools.run_flow(flow=flow, storage=storage, flags=flags, http=httpObj)
  except httplib2.CertificateValidationUnsupported:
    noPythonSSLExit()
  credentials.user_agent = GAM_INFO
  httpObj = credentials.authorize(httplib2.Http(disable_ssl_certificate_validation=GC.Values[GC.NO_VERIFY_SSL],
                                                cache=None))
  return (googleapiclient.discovery.build(u'cloudresourcemanager', u'v1', http=httpObj, cache_discovery=False), httpObj)
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def doUpdateProject():
  login_hint = getEmailAddress(noUid=True, optional=True)
  checkForExtraneousArguments()
  login_hint = getValidateLoginHint(login_hint)
  _, httpObj = getCRMService(login_hint)
  cs_data = readFile(GC.Values[GC.CLIENT_SECRETS_JSON], mode=u'rb', continueOnError=True, displayError=True, encoding=None)
  if not cs_data:
    systemErrorExit(14, u'Your client secrets file:\n\n%s\n\nis missing. Please recreate the file.' % GC.Values[GC.CLIENT_SECRETS_JSON])
  try:
    cs_json = json.loads(cs_data)
    projectName = 'project:%s' % cs_json[u'installed'][u'project_id']
  except (ValueError, IndexError, KeyError):
    systemErrorExit(3, u'The format of your client secrets file:\n\n%s\n\nis incorrect. Please recreate the file.' % GC.Values[GC.CLIENT_SECRETS_JSON])
  simplehttp = httplib2.Http(disable_ssl_certificate_validation=GC.Values[GC.NO_VERIFY_SSL])
  enableProjectAPIs(simplehttp, httpObj, projectName, True)

# gam whatis <EmailItem> [noinfo]
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
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
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def test_put(self):
        session = self.session()
        storage = oauth2client.contrib.sqlalchemy.Storage(
            session=session,
            model_class=DummyModel,
            key_name='key',
            key_value=1,
            property_name='credentials',
        )
        # Store invalid credentials first to verify overwriting
        storage.put(oauth2client.client.Credentials())
        storage.put(self.credentials)
        session.commit()

        entity = session.query(DummyModel).filter_by(key=1).first()
        self.compare_credentials(entity.credentials)
项目:rube-gmail    作者:bonzini    | 项目源码 | 文件源码
def get_credentials(client_secret_file, credentials_file, scopes, user_agent, args=None):
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    store = oauth2client.file.Storage(credentials_file)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = oauth2client.client.flow_from_clientsecrets(client_secret_file, scopes)
        flow.user_agent = user_agent
        if args:
            credentials = oauth2client.tools.run_flow(flow, store, args)
        else: # Needed only for compatibility with Python 2.6
            credentials = oauth2client.tools.run(flow, store)
        print('Storing credentials to ' + credentials_file)
    return credentials



# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/gmail-python-import.json
项目:rube-gmail    作者:bonzini    | 项目源码 | 文件源码
def get_credentials(client_secret_file, credentials_file, scopes, user_agent, args=None):
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    store = oauth2client.file.Storage(credentials_file)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = oauth2client.client.flow_from_clientsecrets(client_secret_file, scopes)
        flow.user_agent = user_agent
        if args:
            credentials = oauth2client.tools.run_flow(flow, store, args)
        else: # Needed only for compatibility with Python 2.6
            credentials = oauth2client.tools.run(flow, store)
        print('Storing credentials to ' + credentials_file)
    return credentials



# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/gmail-python-import.json
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def test_put(self):
        session = self.session()
        storage = oauth2client.contrib.sqlalchemy.Storage(
            session=session,
            model_class=DummyModel,
            key_name='key',
            key_value=1,
            property_name='credentials',
        )
        # Store invalid credentials first to verify overwriting
        storage.put(oauth2client.client.Credentials())
        storage.put(self.credentials)
        session.commit()

        entity = session.query(DummyModel).filter_by(key=1).first()
        self.compare_credentials(entity.credentials)
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
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
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def authorized_http(credentials):
    """Returns an http client that is authorized with the given credentials.

    Args:
        credentials (Union[
            google.auth.credentials.Credentials,
            oauth2client.client.Credentials]): The credentials to use.

    Returns:
        Union[httplib2.Http, google_auth_httplib2.AuthorizedHttp]: An
            authorized http client.
    """
    if HAS_GOOGLE_AUTH and isinstance(
            credentials, google.auth.credentials.Credentials):
        return google_auth_httplib2.AuthorizedHttp(credentials,
                                                   http=build_http())
    else:
        return credentials.authorize(build_http())
项目:hackpad-email-reader    作者:Stek-io    | 项目源码 | 文件源码
def __init__(self, config, logger):
        """
        Constructor
        :param config: Configuration dict
        :param logger: Python logger
        """

        # Suppress cache warnings from gogogle api lib
        logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.ERROR)
        self._client_secret_file = os.path.join(config['credentials_dir'],
                                                config['client_secret_file_name'])
        self._credentials_file = os.path.join(config['credentials_dir'],
                                              config['credentials_file_name'])
        self._logger = logger
        self._config = config
        self._credentials = self._get_credentials()

        # Bootstrap the Gmail client service
        http = self._credentials.authorize(httplib2.Http())
        self._service = discovery.build('gmail', 'v1', http=http)
项目:GAMADV-X    作者:taers232c    | 项目源码 | 文件源码
def getGDataOAuthToken(gdataObj, credentials=None):
  if not credentials:
    credentials = getClientCredentials(API.FAM2_SCOPES)
  try:
    credentials.refresh(httplib2.Http(disable_ssl_certificate_validation=GC.Values[GC.NO_VERIFY_SSL]))
  except httplib2.ServerNotFoundError as e:
    systemErrorExit(NETWORK_ERROR_RC, str(e))
  except oauth2client.client.AccessTokenRefreshError as e:
    return handleOAuthTokenError(str(e), False)
  gdataObj.additional_headers[u'Authorization'] = u'Bearer {0}'.format(credentials.access_token)
  if not GC.Values[GC.DOMAIN]:
    GC.Values[GC.DOMAIN] = credentials.id_token.get(u'hd', u'UNKNOWN').lower()
  if not GC.Values[GC.CUSTOMER_ID]:
    GC.Values[GC.CUSTOMER_ID] = GC.MY_CUSTOMER
  GM.Globals[GM.ADMIN] = credentials.id_token.get(u'email', u'UNKNOWN').lower()
  GM.Globals[GM.OAUTH2_CLIENT_ID] = credentials.client_id
  gdataObj.domain = GC.Values[GC.DOMAIN]
  gdataObj.source = GAM_INFO
  return True
项目:GAMADV-X    作者:taers232c    | 项目源码 | 文件源码
def buildGAPIObject(api):
  GM.Globals[GM.CURRENT_API_USER] = None
  _, httpObj, service, cred_family = getAPIversionHttpService(api)
  credentials = getClientCredentials(cred_family)
  try:
    API_Scopes = set(list(service._rootDesc[u'auth'][u'oauth2'][u'scopes']))
  except KeyError:
    API_Scopes = set(API.VAULT_SCOPES) if api == API.VAULT else set()
  GM.Globals[GM.CURRENT_API_SCOPES] = list(API_Scopes.intersection(credentials.scopes))
  if not GM.Globals[GM.CURRENT_API_SCOPES]:
    systemErrorExit(NO_SCOPES_FOR_API_RC, Msg.NO_SCOPES_FOR_API.format(service._rootDesc[u'title']))
  try:
    service._http = credentials.authorize(httpObj)
  except httplib2.ServerNotFoundError as e:
    systemErrorExit(NETWORK_ERROR_RC, str(e))
  except oauth2client.client.AccessTokenRefreshError as e:
    return handleOAuthTokenError(str(e), False)
  if not GC.Values[GC.DOMAIN]:
    GC.Values[GC.DOMAIN] = credentials.id_token.get(u'hd', u'UNKNOWN').lower()
  if not GC.Values[GC.CUSTOMER_ID]:
    GC.Values[GC.CUSTOMER_ID] = GC.MY_CUSTOMER
  GM.Globals[GM.ADMIN] = credentials.id_token.get(u'email', u'UNKNOWN').lower()
  GM.Globals[GM.OAUTH2_CLIENT_ID] = credentials.client_id
  return service
项目:GAMADV-X    作者:taers232c    | 项目源码 | 文件源码
def doVersion(checkForArgs=True):
  forceCheck = simple = False
  if checkForArgs:
    while Cmd.ArgumentsRemaining():
      myarg = getArgument()
      if myarg == u'check':
        forceCheck = True
      elif myarg == u'simple':
        simple = True
      else:
        unknownArgumentExit()
  if simple:
    writeStdout(__version__)
    return
  import struct
  version_data = u'GAM {0} - {1}\n{2}\nPython {3}.{4}.{5} {6}-bit {7}\ngoogle-api-python-client {8}\noauth2client {9}\n{10} {11}\nPath: {12}\n'
  writeStdout(version_data.format(__version__, GAM_URL, __author__, sys.version_info[0],
                                  sys.version_info[1], sys.version_info[2], struct.calcsize(u'P')*8,
                                  sys.version_info[3], googleapiclient.__version__, oauth2client.__version__, platform.platform(),
                                  platform.machine(), GM.Globals[GM.GAM_PATH]))
  if forceCheck:
    doGAMCheckForUpdates(forceCheck=True)

# gam help
项目:GAMADV-X    作者:taers232c    | 项目源码 | 文件源码
def getCRMService(login_hint):
  from oauth2client.contrib.dictionary_storage import DictionaryStorage
  scope = u'https://www.googleapis.com/auth/cloud-platform'
  client_id = u'297408095146-fug707qsjv4ikron0hugpevbrjhkmsk7.apps.googleusercontent.com'
  client_secret = u'qM3dP8f_4qedwzWQE1VR4zzU'
  flow = oauth2client.client.OAuth2WebServerFlow(client_id=client_id,
                                                 client_secret=client_secret, scope=scope, redirect_uri=oauth2client.client.OOB_CALLBACK_URN,
                                                 user_agent=GAM_INFO, access_type=u'online', response_type=u'code', login_hint=login_hint)
  storage_dict = {}
  storage = DictionaryStorage(storage_dict, u'credentials')
  flags = cmd_flags(noLocalWebserver=GC.Values[GC.NO_BROWSER])
  httpObj = httplib2.Http(disable_ssl_certificate_validation=GC.Values[GC.NO_VERIFY_SSL])
  try:
    credentials = oauth2client.tools.run_flow(flow=flow, storage=storage, flags=flags, http=httpObj)
  except httplib2.CertificateValidationUnsupported:
    noPythonSSLExit()
  credentials.user_agent = GAM_INFO
  httpObj = credentials.authorize(httplib2.Http(disable_ssl_certificate_validation=GC.Values[GC.NO_VERIFY_SSL],
                                                cache=None))
  return (googleapiclient.discovery.build(u'cloudresourcemanager', u'v1', http=httpObj, cache_discovery=False), httpObj)
项目:GAMADV-X    作者:taers232c    | 项目源码 | 文件源码
def doUpdateProject():
  login_hint = getEmailAddress(noUid=True, optional=True)
  checkForExtraneousArguments()
  login_hint = getValidateLoginHint(login_hint)
  _, httpObj = getCRMService(login_hint)
  cs_data = readFile(GC.Values[GC.CLIENT_SECRETS_JSON], mode=u'rb', continueOnError=True, displayError=True, encoding=None)
  if not cs_data:
    systemErrorExit(14, u'Your client secrets file:\n\n%s\n\nis missing. Please recreate the file.' % GC.Values[GC.CLIENT_SECRETS_JSON])
  try:
    cs_json = json.loads(cs_data)
    projectName = 'project:%s' % cs_json[u'installed'][u'project_id']
  except (ValueError, IndexError, KeyError):
    systemErrorExit(3, u'The format of your client secrets file:\n\n%s\n\nis incorrect. Please recreate the file.' % GC.Values[GC.CLIENT_SECRETS_JSON])
  simplehttp = httplib2.Http(disable_ssl_certificate_validation=GC.Values[GC.NO_VERIFY_SSL])
  enableProjectAPIs(simplehttp, httpObj, projectName, True)

# gam whatis <EmailItem> [noinfo]
项目:GAMADV-X    作者:taers232c    | 项目源码 | 文件源码
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
项目:SNH48Live    作者:SNH48Live    | 项目源码 | 文件源码
def get_authenticated_http_client(args, oauth_scopes):
    if args is None:
        args = ArgumentParser().parse_args([])
    if isinstance(oauth_scopes, str):
        # Singleton
        oauth_scopes = [oauth_scopes]
    flow = oauth2client.client.flow_from_clientsecrets(
        CLIENT_SECRETS_FILE,
        scope=' '.join(f'https://www.googleapis.com/auth/{scope}' for scope in oauth_scopes),
        message=MISSING_CLIENT_SECRETS_MESSAGE,
    )
    oauth_credentials_file = CONFIGS_DIR / f'credentials-{",".join(oauth_scopes)}.json'
    storage = oauth2client.file.Storage(oauth_credentials_file)
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = oauth2client.tools.run_flow(flow, storage, args)
    return credentials.authorize(httplib2.Http())
项目:oscars2016    作者:0x0ece    | 项目源码 | 文件源码
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)))
项目:oscars2016    作者:0x0ece    | 项目源码 | 文件源码
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))
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def credentials_from_code(code):
    """ Exchange code for client secrets """
    return oauth2client.client.credentials_from_clientsecrets_and_code(
        _CLIENT_SECRETS, SCOPES, code)
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
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))
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
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))
项目:dsub    作者:googlegenomics    | 项目源码 | 文件源码
def _get_storage_service(credentials):
  """Get a storage client using the provided credentials or defaults."""
  if credentials is None:
    credentials = GoogleCredentials.get_application_default()
  return discovery.build('storage', 'v1', credentials=credentials)
项目:dsub    作者:googlegenomics    | 项目源码 | 文件源码
def _retry_download_check(exception):
  """Return True if we should retry, False otherwise"""
  print_error('Exception during download: %s' % str(exception))
  return isinstance(exception, oauth2client.client.HttpAccessTokenRefreshError)


# Exponential backoff retrying downloads of GCS object chunks.
# Maximum 23 retries.
# Wait 1, 2, 4 ... 64, 64, 64... seconds.
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def buildGAPIServiceObject(api, user):
  userEmail = convertUIDtoEmailAddress(user)
  _, httpObj, service, _ = getAPIversionHttpService(api)
  GM.Globals[GM.CURRENT_API_USER] = userEmail
  GM.Globals[GM.CURRENT_API_SCOPES] = API.getSvcAcctScopes(api)
  credentials = getSvcAcctCredentials(GM.Globals[GM.CURRENT_API_SCOPES], userEmail)
  try:
    service._http = credentials.authorize(httpObj)
  except httplib2.ServerNotFoundError as e:
    systemErrorExit(NETWORK_ERROR_RC, str(e))
  except oauth2client.client.AccessTokenRefreshError as e:
    return (userEmail, handleOAuthTokenError(str(e), True))
  return (userEmail, service)
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def revokeCredentials(credFamilyList):
  httpObj = httplib2.Http(disable_ssl_certificate_validation=GC.Values[GC.NO_VERIFY_SSL])
  for cred_family in credFamilyList:
    credentials = getCredentialsForScope(cred_family)
    if credentials and not credentials.invalid:
      credentials.revoke_uri = oauth2client.GOOGLE_REVOKE_URI
      try:
        credentials.revoke(httpObj)
        time.sleep(2)
      except oauth2client.client.TokenRevokeError as e:
        printErrorMessage(INVALID_TOKEN_RC, str(e))
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def doOAuthRequest():
  client_id, client_secret = getOAuthClientIDAndSecret()
  login_hint = getEmailAddress(noUid=True, optional=True)
  checkForExtraneousArguments()
  selectedScopes = getScopesFromUser()
  if selectedScopes is None:
    return
  login_hint = getValidateLoginHint(login_hint)
  revokeCredentials(API.FAM_LIST)
  flags = cmd_flags(noLocalWebserver=GC.Values[GC.NO_BROWSER])
  httpObj = httplib2.Http(disable_ssl_certificate_validation=GC.Values[GC.NO_VERIFY_SSL])
  for cred_family in API.FAM_LIST:
    scopes = [API.EMAIL_SCOPE, API.PROFILE_SCOPE] # Email Display Scope, always included for client
    i = 0
    for a_scope in API.OAUTH2_SCOPES:
      if cred_family == a_scope[u'credfam']:
        if selectedScopes[i] == u'*':
          scopes.append(a_scope[u'scope'])
        elif selectedScopes[i] == u'R':
          scopes.append(u'{0}.readonly'.format(a_scope[u'scope']))
        elif selectedScopes[i] == u'A':
          scopes.append(u'{0}.action'.format(a_scope[u'scope']))
      i += 1
    flow = oauth2client.client.OAuth2WebServerFlow(client_id=client_id,
                                                   client_secret=client_secret, scope=scopes, redirect_uri=oauth2client.client.OOB_CALLBACK_URN,
                                                   user_agent=GAM_INFO, response_type=u'code', login_hint=login_hint)
    storage = getCredentialsForScope(cred_family, storageOnly=True)
    try:
      oauth2client.tools.run_flow(flow=flow, storage=storage, flags=flags, http=httpObj)
      time.sleep(3)
    except httplib2.CertificateValidationUnsupported:
      noPythonSSLExit()
  entityActionPerformed([Ent.OAUTH2_TXT_FILE, GC.Values[GC.OAUTH2_TXT]])
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def doOAuthExport():
  if Cmd.ArgumentsRemaining():
    exportFile = getString(Cmd.OB_FILE_NAME)
    checkForExtraneousArguments()
  else:
    exportFile = None
  oauth2Export = {}
  if os.path.isfile(GC.Values[GC.OAUTH2_TXT]):
    for cred_family in API.FAM_LIST:
      credentials = getCredentialsForScope(cred_family)
      if credentials and not credentials.invalid:
        oauth2Export[cred_family] = {u'_module': u'oauth2client.client',
                                     u'_class': 'OAuth2Credentials',
                                     u'access_token': credentials.access_token,
                                     u'client_id': credentials.client_id,
                                     u'client_secret': credentials.client_secret,
                                     u'id_token': credentials.id_token,
                                     u'id_token_jwt': credentials.id_token_jwt,
                                     u'invalid': credentials.invalid,
                                     u'refresh_token': credentials.refresh_token,
                                     u'revoke_uri': credentials.revoke_uri,
                                     u'scopes': sorted(list(credentials.scopes)),
                                     u'token_expiry': datetime.datetime.strftime(credentials.token_expiry, u'%Y-%m-%dT%H:%M:%SZ'),
                                     u'token_info_uri': credentials.token_info_uri,
                                     u'token_uri': credentials.token_uri,
                                     u'user_agent': credentials.user_agent}
      else:
        invalidOauth2TxtExit()
  else:
    invalidOauth2TxtExit()
  if exportFile:
    writeFile(exportFile, json.dumps(oauth2Export, ensure_ascii=False, sort_keys=True, indent=2))
    entityModifierNewValueActionPerformed([Ent.OAUTH2_TXT_FILE, GC.Values[GC.OAUTH2_TXT]], Act.MODIFIER_TO, exportFile)
  else:
    writeStdout(json.dumps(oauth2Export, ensure_ascii=False, sort_keys=True, indent=2)+u'\n')

# gam oauth|oauth2 import <FileName>
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def doOAuthImport():
  importFile = getString(Cmd.OB_FILE_NAME)
  checkForExtraneousArguments()
  jsonData = readFile(importFile, u'rb')
  try:
    jsonDict = json.loads(jsonData)
    if u'client_id' in jsonDict:
      importCredentials = oauth2client.client.Credentials.new_from_json(jsonData)
      if not importCredentials or importCredentials.invalid:
        invalidOauth2TxtImportExit(importFile)
      for cred_family in API.FAM_LIST:
        getCredentialsForScope(cred_family, storageOnly=True).put(importCredentials)
    elif (u'credentials' in jsonDict) and (jsonDict.get(u'file_version') == 2):
      for cred_family in API.FAM_LIST:
        importCredentials = getCredentialsForScope(cred_family, filename=importFile)
        if not importCredentials or importCredentials.invalid:
          invalidOauth2TxtImportExit(importFile)
        getCredentialsForScope(cred_family, storageOnly=True).put(importCredentials)
    elif (API.FAM1_SCOPES in jsonDict) and (API.FAM2_SCOPES in jsonDict):
      for cred_family in API.FAM_LIST:
        importCredentials = oauth2client.client.Credentials.new_from_json(json.dumps(jsonDict[cred_family], ensure_ascii=False, sort_keys=True))
        if not importCredentials or importCredentials.invalid:
          invalidOauth2TxtImportExit(importFile)
        getCredentialsForScope(cred_family, storageOnly=True).put(importCredentials)
    else:
      invalidOauth2TxtImportExit(importFile)
  except (KeyError, ValueError):
    invalidOauth2TxtImportExit(importFile)
  entityModifierNewValueActionPerformed([Ent.OAUTH2_TXT_FILE, GC.Values[GC.OAUTH2_TXT]], Act.MODIFIER_FROM, importFile)

# gam <UserTypeEntity> check serviceaccount
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def locked_get(self):
        """Retrieve credential.

        The Storage lock must be held when this is called.

        Returns:
            oauth2client.client.Credentials
        """
        raise NotImplementedError
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def get(self):
        """Retrieve credential.

        The Storage lock must *not* be held when this is called.

        Returns:
            oauth2client.client.Credentials
        """
        self.acquire_lock()
        try:
            return self.locked_get()
        finally:
            self.release_lock()
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
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)
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def default_credentials():
    """Returns Application Default Credentials."""
    if HAS_GOOGLE_AUTH:
        credentials, _ = google.auth.default()
        return credentials
    elif HAS_OAUTH2CLIENT:
        return oauth2client.client.GoogleCredentials.get_application_default()
    else:
        raise EnvironmentError(
            'No authentication library is available. Please install either '
            'google-auth or oauth2client.')
项目:containerregistry    作者:google    | 项目源码 | 文件源码
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
项目:office-interoperability-tools    作者:milossramek    | 项目源码 | 文件源码
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))
项目:office-interoperability-tools    作者:milossramek    | 项目源码 | 文件源码
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))
项目:professional-services    作者:GoogleCloudPlatform    | 项目源码 | 文件源码
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
项目:professional-services    作者:GoogleCloudPlatform    | 项目源码 | 文件源码
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
项目:hashtagtodo-open    作者:slackpad    | 项目源码 | 文件源码
def retrieve_discovery_doc(serviceName, version,
                           discoveryServiceUrl=DISCOVERY_URI):
    params = {'api': serviceName, 'apiVersion': version}
    requested_url = uritemplate.expand(discoveryServiceUrl, params)

    # REMOTE_ADDR is defined by the CGI spec [RFC3875] as the environment
    # variable that contains the network address of the client sending the
    # request. If it exists then add that to the request for the discovery
    # document to avoid exceeding the quota on discovery requests.
    if 'REMOTE_ADDR' in os.environ:
        requested_url = _add_query_parameter(requested_url, 'userIp',
                                             os.environ['REMOTE_ADDR'])

    http = httplib2.Http()
    resp, content = http.request(requested_url)
    if resp.status >= 400:
        raise HttpError(resp, content, uri=requested_url)

    try:
        service = json.loads(content)
    except ValueError:
        raise InvalidJsonError(
            'Bad JSON: %s from %s.' % (content, requested_url))

    # We return content instead of the JSON deserialized service because
    # build_from_document() consumes a string rather than a dictionary.
    return content
项目:hashtagtodo-open    作者:slackpad    | 项目源码 | 文件源码
def make_client(user):
    credentials = AUTHOMATIC.credentials(user.credentials)

    # The token refresh will be a no-op if it's not due to expire soon.
    orig_token = credentials.token
    credentials.refresh(soon=TOKEN_REFRESH_SECONDS)
    if credentials.token != orig_token:
        user.credentials = credentials.serialize()
        user.put()

    # TODO - The code from here down will only work for Google clients. We
    # should generalize a bit.

    # The refresh here should never be used, but we add it here just so
    # requests will go through if we get into a weird state.
    oauth_credentials = oauth2client.client.OAuth2Credentials(
        access_token=credentials.token,
        client_id=credentials.consumer_key,
        client_secret=credentials.consumer_secret,
        refresh_token=credentials.refresh_token,
        token_expiry=credentials.expiration_date,
        token_uri=credentials.provider_class.access_token_url,
        user_agent=USER_AGENT)

    http = httplib2.Http()
    http = oauth_credentials.authorize(http)
    return DiscoveryDocument.build('calendar', 'v3', http=http)
项目:BoilerPlate    作者:wyaron    | 项目源码 | 文件源码
def get_calendar_events(start_utc_time, end_utc_time, maxEvents=5):
  global service

  if service is None:
     init()
     authenticate()

  # did it work ? if not, the client of this class should retry
  if service is None:
     raise Exception('can not connect to google calendar')

  logging.getLogger('BoilerLogger').debug("Getting calendar events from: %s to %s" % (start_utc_time, end_utc_time))
  events = service.events().list(calendarId=CALENDAR_ID, orderBy="startTime",
                                 singleEvents=True, timeMin=start_utc_time, timeMax=end_utc_time, maxResults=maxEvents).execute()                
  return events['items']
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def setUp(self):
        engine = sqlalchemy.create_engine('sqlite://')
        Base.metadata.create_all(engine)

        self.session = sqlalchemy.orm.sessionmaker(bind=engine)
        self.credentials = oauth2client.client.OAuth2Credentials(
            access_token='token',
            client_id='client_id',
            client_secret='client_secret',
            refresh_token='refresh_token',
            token_expiry=datetime.datetime.utcnow(),
            token_uri=oauth2client.GOOGLE_TOKEN_URI,
            user_agent='DummyAgent',
        )
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def test_get(self, set_store):
        session = self.session()
        credentials_storage = oauth2client.contrib.sqlalchemy.Storage(
            session=session,
            model_class=DummyModel,
            key_name='key',
            key_value=1,
            property_name='credentials',
        )
        # No credentials stored
        self.assertIsNone(credentials_storage.get())

        # Invalid credentials stored
        session.add(DummyModel(
            key=1,
            credentials=oauth2client.client.Credentials(),
        ))
        session.commit()
        bad_credentials = credentials_storage.get()
        self.assertIsInstance(bad_credentials, oauth2client.client.Credentials)
        set_store.assert_not_called()

        # Valid credentials stored
        session.query(DummyModel).filter_by(key=1).delete()
        session.add(DummyModel(
            key=1,
            credentials=self.credentials,
        ))
        session.commit()

        self.compare_credentials(credentials_storage.get())
        set_store.assert_called_with(credentials_storage)
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def locked_get(self):
        """Retrieve credential.

        The Storage lock must be held when this is called.

        Returns:
            oauth2client.client.Credentials
        """
        raise NotImplementedError
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def get(self):
        """Retrieve credential.

        The Storage lock must *not* be held when this is called.

        Returns:
            oauth2client.client.Credentials
        """
        self.acquire_lock()
        try:
            return self.locked_get()
        finally:
            self.release_lock()
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def __init__(self, access_token, client_id, client_secret, refresh_token,
                 token_expiry, token_uri, user_agent,
                 revoke_uri=oauth2client.GOOGLE_REVOKE_URI):
        """Create an instance of GoogleCredentials.

        This constructor is not usually called by the user, instead
        GoogleCredentials objects are instantiated by
        GoogleCredentials.from_stream() or
        GoogleCredentials.get_application_default().

        Args:
            access_token: string, access token.
            client_id: string, client identifier.
            client_secret: string, client secret.
            refresh_token: string, refresh token.
            token_expiry: datetime, when the access_token expires.
            token_uri: string, URI of token endpoint.
            user_agent: string, The HTTP User-Agent to provide for this
                        application.
            revoke_uri: string, URI for revoke endpoint. Defaults to
                        oauth2client.GOOGLE_REVOKE_URI; a token can't be
                        revoked if this is None.
        """
        super(GoogleCredentials, self).__init__(
            access_token, client_id, client_secret, refresh_token,
            token_expiry, token_uri, user_agent, revoke_uri=revoke_uri)
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
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)