Commit 59a42523 authored by Rob Carleski's avatar Rob Carleski 🇮🇸
Browse files

Make create_shared more tolerant of API responses.

parent 959293d3
......@@ -12,7 +12,8 @@ import yaml
from boxsdk.object.collaboration import CollaborationRole
from subprocess import check_output as cmd
from subprocess import CalledProcessError
from time import sleep
devnull = open(os.devnull, 'w')
class SharedAccount:
......@@ -64,7 +65,6 @@ class SharedAccount:
self.box_text = '''
Box-Specific Information:
- The ability to use Box Sync with shared accounts is disabled by default,
but allowed in certain circumstances; if you need this, please reply to this
message to discuss. Syncing the shared folder in your individual account is
......@@ -152,54 +152,66 @@ http://its.umich.edu/help/'''.format(self.full_name, self.email)
self.password,
'org',
'Department accounts'
])
], stderr=devnull)
except CalledProcessError as e:
self.logger.error(e, extra={'entity': self.account})
if e.returncode == 144:
self.logger.info(
'Invalid data provided to Google account creation call',
extra={'entity': self.account}
)
elif e.returncode == 153:
self.logger.info(
'Account already exists in Google',
extra={'entity': self.account}
)
else:
self.logger.error(e, extra={'entity': self.account})
self.google_text = '''
Google-Specific Information:
- For information on using this account, please check the following URL:
https://documentation.its.umich.edu/node/339/
https://documentation.its.umich.edu/node/339/
'''
def set_up_mcommunity_group(self):
mcommClient = mcommunity.Client(self.config['mcommunity'])
try:
mcommClient.fetch_group(self.account)
except Exception as e:
self.logger.info(e, extra={'entity': self.account})
if hasattr(mcommClient, 'group_data'):
controllerCn = mcommClient._create_entity_ldap(
self.config['mcommunity']['api_control_group']
)
print(mcommClient.group_data)
if controllerCn not in mcommClient.group_data['ownerDn']:
if self.take_group_ownership(self.account):
mcommClient.fetch_group(self.account)
self.logger.debug(
'Waiting 10 seconds for replication.',
extra={'entity': self.account}
)
sleep(1)
else:
if not self.take_group_ownership(self.account):
self.logger.error(
'Failed to obtain group ownership.',
extra={'entity': self.account}
)
exit(2)
except Exception:
mcommClient.reserve_group(self.account)
self.logger.debug(
'Waiting 10 seconds for replication.',
extra={'entity': self.account}
)
sleep(1)
mcommClient.add_group_owners(self.owners)
mcommClient.fetch_group(self.account)
else:
try:
mcommClient.reserve_group(self.account)
mcommClient.fetch_group(self.account)
except Exception as e:
self.logger.info(e, extra={'entity': self.account})
exit(2)
try:
if self.services in ['google', 'both']:
if self.service in ['google', 'both']:
email = self.account + '@go.itd.umich.edu'
mcommClient.add_group_members(email)
mcommClient.remove_group_owners('collab-api-client')
mcommClient.update_group_members()
mcommClient.add_group_owners(self.owners)
mcommClient.remove_group_owners(
self.config['mcommunity']['api_control_group']
)
mcommClient.update_group_owners()
except Exception as e:
self.logger.warning(e, extra={'entity': self.account})
......@@ -225,11 +237,10 @@ Google-Specific Information:
self.password
)
except kadmin.KAdminError as e:
self.logger.error(e, extra={'entity': self.account})
exit(2)
self.logger.warning(e, extra={'entity': self.account})
def upload_and_share_password(self):
passFilePath = '{}/{}-passwd'.format(
passFilePath = '{}/{}-passwd.txt'.format(
self.config['general']['data_dir'],
self.account
)
......@@ -247,7 +258,7 @@ Google-Specific Information:
passFilePath,
'parentname',
'Shared Account Passwords'
])
], stderr=devnull)
file_id = re.search(
r'.*\((.*)\)',
upload_output.decode('UTF-8')
......@@ -286,6 +297,8 @@ Google-Specific Information:
self.last_name
)
self.account = re.sub(r'[^\w_-]', '.', self.account).lower().strip()
self.email = '{}@{}'.format(
self.account,
self.config['google']['domain']
......@@ -331,7 +344,7 @@ def main():
nargs='+'
)
parser.add_argument(
'--services',
'--service',
'-s',
help='The type of account(s) to create',
choices=[
......@@ -345,13 +358,11 @@ def main():
'--first_name',
'-f',
help='The first name to use for the account',
required=True
)
parser.add_argument(
'--last_name',
'-l',
help='The last name to use for the account',
required=True
)
parser.add_argument(
'--secure',
......@@ -391,12 +402,13 @@ def main():
sa = SharedAccount(vars(args), config)
sa.set_up_mcommunity_group()
exit(2)
sa.set_kerberos_password()
if sa.service in ['box', 'both']:
sa.create_box()
if sa.service in ['google', 'both']:
sa.create_google()
sa.upload_and_share_password()
pass_file_id = sa.upload_and_share_password()
header_text = '''
Hello,
......@@ -404,18 +416,19 @@ Hello,
Your request has been completed. The password for your shared account
can be found at the following link:
{}
https://docs.google.com/a/{}/file/d/{}
We recommend using a Chrome incognito window or separate browser to log
into your shared account. Please see below for more information about the
shared account created per your request:
General Account Information:
Display Name: {}
Username: {}
Email Address: {}
- Display Name: {}
- Username: {}
- Email Address: {}
'''.format(
'https://docs.google.com/a/umich.edu/file/d/' + sa.pass_file_id + '/',
config['google']['domain'],
pass_file_id,
sa.full_name,
sa.account,
sa.email,
......@@ -436,8 +449,8 @@ about your new account and the ticket will be re-opened.
print(
'========== CANNED TEXT ==========',
header_text,
sa.box_text,
sa.google_text,
sa.box_text if hasattr(sa, 'box_text') else '',
sa.google_text if hasattr(sa, 'google_text') else '',
footer_text
)
......
......@@ -15,7 +15,7 @@ with open(os.path.join(os.path.dirname(__file__), 'README.md'), 'r') as f:
test_deps = [
'boxsdk[jwt]',
'kadmin',
'mcommunity',
'mcommunity @ git+https://gitlab.umich.edu/carleski/python-mcommunity.git',
'pytest',
'pytest-pep8',
'pyyaml',
......@@ -52,7 +52,7 @@ setup(
install_requires=[
'boxsdk[jwt]',
'kadmin',
'mcommunity',
'mcommunity @ git+https://gitlab.umich.edu/carleski/python-mcommunity.git',
'requests',
'pyyaml'
],
......
......@@ -12,13 +12,11 @@ def get_testdata(base, name):
with open(fname, 'r') as f:
return f.read()
else:
raise Exception()
# return '{}'
raise Exception('hurk. blah.')
class Client:
group_data = {}
group_reserved = False
def __init__(self):
......@@ -33,8 +31,9 @@ class Client:
if self.group_reserved:
return True
else:
group_data = get_testdata('profile', group)
self.group_data = json.loads(
get_testdata('profile', group)
group_data
)['group'][0]
def reserve_group(self, group):
......
......@@ -95,4 +95,5 @@ def test_create_extra_attr():
del(sa.last_name)
sa.account = delim.join(['test', 'shared', 'account'])
sa.create_extra_attr()
assert ' ' not in sa.account
assert sa.full_name == 'Test Shared Account'
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment