in output/mail.py [0:0]
def expand_recipients(self, mail, config):
"""Expands group recipients using the Directory API"""
to_emails = []
try:
to_emails = email.utils.getaddresses([mail['mail_to']],
strict=False)
except TypeError:
to_emails = email.utils.getaddresses([mail['mail_to']])
self.logger.debug('Starting expansion of group recipients...',
extra={'to': to_emails})
service_account = config[
'serviceAccountEmail'] if 'serviceAccountEmail' in config else None
user_credentials = Credentials(
self.get_token_for_scopes([
'https://www.googleapis.com/auth/admin.directory.user.readonly'
],
service_account=service_account))
group_credentials = Credentials(
self.get_token_for_scopes([
'https://www.googleapis.com/auth/cloud-identity.groups.readonly'
],
service_account=service_account))
user_service = discovery.build('admin',
'directory_v1',
credentials=user_credentials)
group_service = discovery.build('cloudidentity',
'v1beta1',
credentials=group_credentials)
new_emails = []
for e in to_emails:
request = group_service.groups().lookup()
request.uri += "&groupKey.id=" + e[1]
try:
response = request.execute()
except errors.HttpError as exc:
if exc.resp.status == 404 or exc.resp.status == 403:
self.logger.debug(
'Did not find group %s in Cloud Identity.' % (e[1]),
extra={'response': exc.resp})
response = None
else:
raise exc
if response and 'name' in response:
m_request = group_service.groups().memberships().list(
parent=response['name'])
m_response = m_request.execute()
if 'memberships' in m_response: # If this field doesn't exist, it's probably an empty group
for membership in m_response['memberships']:
new_emails.append(
email.utils.formataddr(
('', membership['memberKey']['id'])))
else:
try:
u_response = user_service.users().get(
userKey=e[1]).execute()
if u_response:
new_emails.append(e[1])
except errors.HttpError as exc:
if 'ignoreNonexistentGroups' not in config or not config[
'ignoreNonexistentGroups']:
raise GroupNotFoundException(
'Failed to find group %s in Cloud Identity!' % e[1])
elif 'ignoreNonexistentGroups' in config and isinstance(
config['ignoreNonexistentGroups'],
str) and not e[1].endswith(
config['ignoreNonexistentGroups']):
new_emails.append(e[1])
else:
self.logger.debug('Non-existent user %s skipped.' %
(e[1]),
extra={'response': exc.resp})
new_to = ''
for e in new_emails:
new_to += ', ' if new_to != '' else ''
new_to += e
mail['mail_to'] = new_to
self.logger.debug('Finished expanding group recipients.',
extra={'to': new_to})
return mail