create_shared.py 13.9 KB
Newer Older
1
#!/usr/bin/env python3
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import argparse
import boxsdk
import kadmin
import logging
import logging.handlers
import mcommunity
import os
import re
import yaml

from boxsdk.object.collaboration import CollaborationRole
from subprocess import check_output as cmd
from subprocess import CalledProcessError
from time import sleep


class SharedAccount:

    def __init__(self, args, config):
        self.__dict__.update(args)
        self.config = config
        self.create_extra_attr()
Rob Carleski's avatar
Rob Carleski committed
24
        self.logger = logging.getLogger(__name__)
25
26
27
28
29
30
31
32

    def create_box(self):
        try:
            auth = boxsdk.JWTAuth.from_settings_file(
                self.config['box']['auth_file']
            )
            boxClient = boxsdk.Client(auth)
        except IOError as e:
Rob Carleski's avatar
Rob Carleski committed
33
            self.logger.error(e, extra={'entity': self.account})
34
35
            exit(2)
        except boxsdk.exception.BoxAPIException as e:
Rob Carleski's avatar
Rob Carleski committed
36
            self.logger.error(e, extra={'entity': self.account})
37
38
39
40
            exit(2)

        try:
            if len(self.full_name) > 50:
Rob Carleski's avatar
Rob Carleski committed
41
                self.logger.warning(
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
                    'Full name attribute for user exceeds limit. Truncating.',
                    extra={'entity': self.account}
                )
            boxAccount = boxClient.create_user(
                name=self.full_name[:50],
                login=self.email,
                space_amount=-1,
                tracking_codes={
                    'name': 'account_type',
                    'value': 'shared'
                }
            )

            boxAccount.update_info({'is_sync_enabled': False})

            self.shared_box_folder = boxClient.as_user(
                boxAccount
            ).folder(
                0
            ).create_subfolder(
                self.full_name
            )

            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
always allowed.

 - Files placed in shared account folders are owned by the shared account.

 - To learn more about using your shared account, visit the Shared U-M Box
Accounts section of the M+Box support site.

(http://www.itcs.umich.edu/storage/box/shared-accounts.php)

'''
            if self.secure:
                self.shared_box_folder.update_info({
                    'can_non_owners_invite': False,
                    'allowed_shared_link_access_levels': ['collaborators']
                })
                self.box_text += '''
 - Settings appropriate for sensitive data have been applied to this folder.
'''

            self.upload_box_info_file()

            for owner in self.owners:
                search = boxClient.users(filter_term=owner)
                for _ in search:
                    login = _['login'].split('@')[0].lower()
                    if owner.lower() == login:
                        try:
                            self.shared_box_folder.collaborate(
                                _,
                                CollaborationRole.CO_OWNER
                            )
                        except boxsdk.exception.BoxAPIException as e:
Rob Carleski's avatar
Rob Carleski committed
103
                            self.logger.warning(
104
105
106
107
108
109
110
                                'Unable to add {} as Box collaborator'.format(
                                    _
                                 ),
                                extra={'entity': self.account}
                            )
                        break
        except boxsdk.exception.BoxAPIException as e:
Rob Carleski's avatar
Rob Carleski committed
111
            self.logger.error(e, extra={'entity': self.account})
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135

    def upload_box_info_file(self):
        try:
            readme = '{}/{}-{}'.format(
                self.config['general']['data_dir'],
                self.account,
                'README.txt'
            )
            with open(readme, 'w+') as stream:
                content = '''
The folder "{}" is owned by the shared account "{}".

The initial co-owners on this folder are based on the owners listed on the
request form at the time this folder was created.

The co-owners and members will NOT be kept in sync with MCommunity.

f you have any questions please contact the ITS Service Center:

http://its.umich.edu/help/'''.format(self.full_name, self.email)
                stream.write(content)
            self.shared_box_folder.upload(readme)
            os.remove(readme)
        except IOError as e:
Rob Carleski's avatar
Rob Carleski committed
136
            self.logger.error(e, extra={'entity': self.account})
137
        except boxsdk.exception.BoxAPIException as e:
Rob Carleski's avatar
Rob Carleski committed
138
            self.logger.error(e, extra={'entity': self.account})
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156

    def create_google(self):
        try:
            cmd([
                self.config['google']['gam_command'],
                'create',
                'user',
                self.account,
                'firstname',
                self.first_name,
                'lastname',
                self.last_name,
                'password',
                self.password,
                'org',
                'Department accounts'
            ])
        except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
157
            self.logger.error(e, extra={'entity': self.account})
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177

        self.google_text = '''
Google-Specific Information:

- For information on using this account, please check the following URL:

    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)
            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)
Rob Carleski's avatar
Rob Carleski committed
178
                    self.logger.debug(
179
180
181
182
183
                        'Waiting 10 seconds for replication.',
                        extra={'entity': self.account}
                    )
                    sleep(1)
                else:
Rob Carleski's avatar
Rob Carleski committed
184
                    self.logger.error(
185
186
187
188
189
190
                        'Failed to obtain group ownership.',
                        extra={'entity': self.account}
                    )
                    exit(2)
        except Exception:
            mcommClient.reserve_group(self.account)
Rob Carleski's avatar
Rob Carleski committed
191
            self.logger.debug(
192
193
194
195
196
197
198
199
200
201
202
203
                'Waiting 10 seconds for replication.',
                extra={'entity': self.account}
            )
            sleep(1)
            mcommClient.add_group_owners(self.owners)

        try:
            if self.services in ['google', 'both']:
                email = self.account + '@go.itd.umich.edu'
                mcommClient.add_group_members(email)
            mcommClient.remove_group_owners('collab-api-client')
        except Exception as e:
Rob Carleski's avatar
Rob Carleski committed
204
            self.logger.warning(e, extra={'entity': self.account})
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227

    def take_group_ownership(self, group):
        input('Add api controller as group owner, then press enter.')
        return True

    def set_kerberos_password(self):
        try:
            admin = '{}@{}'.format(
                self.config['kerberos']['admin'],
                self.config['kerberos']['realm'].upper()
            )
            kadm = kadmin.init_with_keytab(
                admin,
                self.config['kerberos']['keytab']
            )
            kadm.ank(
                '{}@{}'.format(
                    self.account,
                    self.config['kerberos']['realm'].upper()
                ),
                self.password
            )
        except kadmin.KAdminError as e:
Rob Carleski's avatar
Rob Carleski committed
228
            self.logger.error(e, extra={'entity': self.account})
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
            exit(2)

    def upload_and_share_password(self):
        passFilePath = '{}/{}-passwd'.format(
            self.config['general']['data_dir'],
            self.account
        )

        with open(passFilePath, 'w') as passwordFile:
            passwordFile.write(self.password)

        upload_output = cmd([
            self.config['google']['gam_command'],
            'user',
            self.config['google']['admin_account'],
            'add',
            'drivefile',
            'localfile',
            passFilePath,
            'parentname',
            'Shared Account Passwords'
        ])
        file_id = re.search(
            r'.*\((.*)\)',
            upload_output.decode('UTF-8')
        ).groups()[0]

        for owner in self.owners:
            try:
                cmd([
                    self.config['google']['gam_command'],
                    'user',
                    self.config['google']['admin_account'],
                    'add',
                    'drivefileacl',
                    file_id,
                    'user',
                    owner,
                    'role',
                    'reader'
                ])
            except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
271
                self.logger.warning(e.output, extra={'entity': self.account})
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
                continue

        os.remove(passFilePath)
        return file_id

    def create_extra_attr(self):
        try:
            self.full_name = self.first_name + self.last_name
        except AttributeError:
            split = re.split(r'[\-\_\.\s]+', self.account)
            self.first_name = ' '.join(split[:len(split)//2]).title()
            self.last_name = ' '.join(split[len(split)//2:]).title()
            self.full_name = '{} {}'.format(
                self.first_name,
                self.last_name
            )

        self.email = '{}@{}'.format(
            self.account,
            self.config['google']['domain']
        )


def main():
    helptext = '''examples:
        collab-create-shared -a collab-testing -p pass12word -o mlkjr moliere
        collab-create-shared -a collab-testing -f collab -l testing -t google
            -p pass12word -o mlkjr moliere -s
        collab-create-shared --account collab-testing --password pass12word
            --owners mlkjr moliere
        collab-create-shared --acount collab-testing --password pass12word
            --owners mlkdir moliere --first_name collab --last_name testing
            --type box --secure

        Note: If first and last names are not provided, they will be set
            automatically using common delimiters
        '''

    parser = argparse.ArgumentParser(
        description='Creates shared accounts in collab services',
        epilog=helptext,
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument(
        '--account',
        '-a',
        help='The account name to use.',
        required=True
    )
    parser.add_argument(
        '--password',
        '-p',
        help='The password to use for the account',
        required=True
    )
    parser.add_argument(
        '--owners',
        '-o',
        help='Owners for the shared account',
        nargs='+'
    )
    parser.add_argument(
        '--services',
        '-s',
        help='The type of account(s) to create',
        choices=[
            'google',
            'box',
            'both'
        ],
        default='both'
    )
    parser.add_argument(
        '--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',
        help='Secure the account for sensitive data',
        action='store_true'
    )
    parser.add_argument(
        '--config',
        '-c',
        help='The CAK config to use for Google operations',
        default='/etc/collab-admin-kit.yml'
    )
    args = parser.parse_args()

    # Open the CAK Config
    with open(args.config) as stream:
        config = yaml.load(stream, Loader=yaml.BaseLoader)

    # Get the root logger and set the debug level
Rob Carleski's avatar
Rob Carleski committed
374
    logger = logging.getLogger(__name__)
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
    logger.setLevel(logging.DEBUG)

    # Create a syslog handler, set format, and associate.
    sh = logging.handlers.SysLogHandler(
        address='/dev/log',
        facility=config['general']['log_facility']
    )
    formatter = logging.Formatter(config['general']['log_format'])
    sh.setFormatter(formatter)
    logger.addHandler(sh)

    # Create a console handler, set format, and associate.
    ch = logging.StreamHandler()
    formatter = logging.Formatter(config['general']['console_format'])
    ch.setFormatter(formatter)
    logger.addHandler(ch)

392
    sa = SharedAccount(vars(args), config)
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
    sa.set_up_mcommunity_group()
    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()

    header_text = '''
Hello,

Your request has been completed. The password for your shared account
can be found at the following link:

{}

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: {}
'''.format(
        'https://docs.google.com/a/umich.edu/file/d/' + sa.pass_file_id + '/',
        sa.full_name,
        sa.account,
        sa.email,
    )

    footer_text = '''
Single-Sign On is used for both Box and Google, and the method of changing
the password is the same for both. For information on changing the password,
please check the documentation found here:

https://documentation.its.umich.edu/node/339/#password

I will be closing this ticket now, as your request has been completed, but
feel free to reply back to this email if you have any questions or concerns
about your new account and the ticket will be re-opened.
'''

    print(
        '========== CANNED TEXT ==========',
        header_text,
        sa.box_text,
        sa.google_text,
        footer_text
    )


if __name__ == '__main__':
    main()