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
python类client()的实例源码
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
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
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)
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]
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
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)
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
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
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)
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
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())
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)
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
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
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
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)
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]
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
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())
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)))
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))
def credentials_from_code(code):
""" Exchange code for client secrets """
return oauth2client.client.credentials_from_clientsecrets_and_code(
_CLIENT_SECRETS, SCOPES, code)
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))
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))
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)
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.
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)
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))
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]])