Note: The default ITS GitLab runner is a shared resource and is subject to slowdowns during heavy usage.
You can run your own GitLab runner that is dedicated just to your group if you need to avoid processing delays.

mcommunity.py 23.6 KB
Newer Older
Rob Carleski's avatar
V2    
Rob Carleski committed
1
import hashlib
Rob Carleski's avatar
Rob Carleski committed
2
3
4
import requests
import json

Rob Carleski's avatar
V2    
Rob Carleski committed
5
6
7
8
from . import core
from time import sleep
from ldap3.utils.dn import parse_dn
from ldap3.core.exceptions import LDAPInvalidDnError
Rob Carleski's avatar
Rob Carleski committed
9
10
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
Rob Carleski's avatar
V2    
Rob Carleski committed
11
12
from requests.exceptions import Timeout
from urllib.parse import quote
13

Rob Carleski's avatar
Rob Carleski committed
14

Rob Carleski's avatar
V2    
Rob Carleski committed
15
class MCommSession(requests.Session):
Rob Carleski's avatar
Rob Carleski committed
16

Rob Carleski's avatar
V2    
Rob Carleski committed
17
    def __init__(self, client_id, secret, **kwargs):
Rob Carleski's avatar
Rob Carleski committed
18

Rob Carleski's avatar
V2    
Rob Carleski committed
19
20
21
22
23
24
25
        super(MCommSession, self).__init__(**kwargs)
        url_base = 'https://apigw.it.umich.edu/um'
        token_url = ('{}/inst/oauth2/token?'
                     'grant_type=client_credentials&'
                     'scope=iamgroups'.format(url_base)
                     )
        self.call_url = url_base + '/iamGroups'
Rob Carleski's avatar
Rob Carleski committed
26
27
28
29

        self.session = requests.Session()
        retries = Retry(
            total=5,
30
            backoff_factor=1,
Rob Carleski's avatar
Rob Carleski committed
31
32
            status_forcelist=[500, 502, 503, 504]
        )
Rob Carleski's avatar
V2    
Rob Carleski committed
33
34
35
36
37

        self.headers.update({
            'accept': 'application/json'
        })

Rob Carleski's avatar
Rob Carleski committed
38
        self.session.mount('http://', HTTPAdapter(max_retries=retries))
39
        self.session.mount('https://', HTTPAdapter(max_retries=retries))
Rob Carleski's avatar
Rob Carleski committed
40
41

        try:
Rob Carleski's avatar
V2    
Rob Carleski committed
42
            self._request_token(token_url, client_id, secret)
Rob Carleski's avatar
Rob Carleski committed
43
44
45
        except KeyError:
            raise KeyError('Unable to get access token from API')

Rob Carleski's avatar
V2    
Rob Carleski committed
46
47
        self.headers.update({
            'x-ibm-client-id': '{}'.format(client_id),
Rob Carleski's avatar
Rob Carleski committed
48
            'authorization': 'Bearer {}'.format(self.token),
Rob Carleski's avatar
V2    
Rob Carleski committed
49
        })
Rob Carleski's avatar
Rob Carleski committed
50

Rob Carleski's avatar
V2    
Rob Carleski committed
51
52
    def _request_token(self, token_url, client_id, secret):
        """Request a token from the MCommunity API
Rob Carleski's avatar
Rob Carleski committed
53

Rob Carleski's avatar
V2    
Rob Carleski committed
54
55
56
57
58
        Parameters
        ----------
        token_url : string
        client_id : string
        secret : string
Rob Carleski's avatar
Rob Carleski committed
59

Rob Carleski's avatar
V2    
Rob Carleski committed
60
61
62
63
64
65
66
67
68
69
70
71
        Returns
        -------
        None
        """

        r = self.post(
            token_url,
            data=json.dumps({
                'grant_type': 'client_credentials',
                'scope': 'constituents'
            }),
            auth=(client_id, secret)
Rob Carleski's avatar
Rob Carleski committed
72
73
74
75
        )

        self.token = r.json()['access_token']

Rob Carleski's avatar
V2    
Rob Carleski committed
76
77
    def request(self, method, url, **kwargs):
        """Patched version of requests.Session.request with magic
Rob Carleski's avatar
Rob Carleski committed
78
79
80

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
81
82
        method : string
        url : string
Rob Carleski's avatar
Rob Carleski committed
83
84
85

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
86
        obj : A magic request object
Rob Carleski's avatar
Rob Carleski committed
87
88
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
        if not url.lower().startswith('http'):
            url = ''.join([self.call_url, url])
        return super(MCommSession, self).request(method, url, **kwargs)


class MCommGroup:

    def __init__(self, client, name):
        self.client = client
        self.name = name
        self.fetch()

    @property
    def exists(self):
        return bool(self.dn)

    @property
    def expandedMembers(self):
        if not hasattr(self, '_expandedMembers'):
            groups = set([self.name])
            processed = set()
            members = set()
            while groups != processed:
                for group in groups.difference(processed):
                    processed.add(group)
                    _group = MCommGroup(self.client, group)
                    groups.update(_group.memberGroups)
                    members.update(_group.members)
            self._expandedMembers = list(members)
        return self._expandedMembers

    @property
    def externalMembers(self):
        if not hasattr(self, '_externalMembers'):
            self._externalMembers = [x['dn'] for x in self.memberExternal]
        return self._externalMembers

    @property
    def links(self):
        if not hasattr(self, '_links'):
            self._links = [x['labeledUri'] for x in self.urlLinks]
        return self._links

    @property
    def members(self):
        if not hasattr(self, '_members'):
            self._members = [parse_dn(x)[0][1] for x in self.memberDn]
        return self._members

    @property
    def memberGroups(self):
        if not hasattr(self, '_memberGroups'):
            self._memberGroups = [
                parse_dn(x)[0][1] for x in self.memberGroupDn
            ]
        return self._memberGroups

    @property
    def moderators(self):
        if not hasattr(self, '_moderators'):
            self._moderators = [x['dn'] for x in self.moderator]
        return self._moderators

    @property
    def owners(self):
        if not hasattr(self, '_owners'):
            self._owners = [parse_dn(x)[0][1] for x in self.ownerDn]
        return self._owners

158
    def fetch(self, targets=None):
Rob Carleski's avatar
V2    
Rob Carleski committed
159
        """Fetch information for an mcommunity group
Rob Carleski's avatar
Rob Carleski committed
160
161

        Parameters
Rob Carleski's avatar
V2    
Rob Carleski committed
162
163
164
        ----------
        targets : list
            Only fetch new data for attributes in this list
Rob Carleski's avatar
Rob Carleski committed
165
166
167

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
168
        None
Rob Carleski's avatar
Rob Carleski committed
169
        """
Rob Carleski's avatar
V2    
Rob Carleski committed
170

Rob Carleski's avatar
Rob Carleski committed
171
172
173
174
        try:
            self.dn = core.get_entity_dn(self.client, self.name)
        except core.MCommEntityNotFound:
            self.dn = None
175
176
177
178
179
180
181
182
183
184
185
186
187
188

        if not self.dn:
            return

        # Updated data isn't always available immediately, so try to loop
        # for a bit if we don't see any change.
        # FIXME: people might call fetch when there actually haven't been any
        # changes, so this should probably be controlled by a flag.
        for i in range(5):
            r = self.client.get(
                url='/profile/dn/{}'.format(quote(self.dn))
            )
            if not r.ok:
                raise core.MCommError('{}: {}'.format(
189
                        r.status_code,
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
                        r.text,
                    )
                )

            group = r.json()['group'][0]
            group['owners_details'] = group.pop('owners')
            new_hash = hashlib.md5(
                json.dumps(group, sort_keys=True).encode('utf-8')
            )
            new_hash = new_hash.hexdigest()
            if getattr(self, 'group_hash', None) != new_hash:
                self.group_hash = new_hash
                break

            if i < 4:
                sleep(2**i)

        if not getattr(self, 'group_hash', None):
            raise core.MCommError('Unable to fetch fresh group data')

        group['objectClass'] = [x.lower() for x in group['objectClass']]
        if 'umichgroup' not in group['objectClass']:
            raise core.MCommError(
                    'Entity found is {}, not group'.format(
                        ', '.join(group['objectClass'])
Rob Carleski's avatar
V2    
Rob Carleski committed
215
                    )
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
                )

        if targets:
            for target in targets:
                setattr(self, target, group[target])
        else:
            self.__dict__.update(group)

        # Make sure that our list attrs are at least empty lists
        for attr in [
            'memberDn',
            'memberExternal',
            'memberGroupDn',
            'moderator',
            'ownerDn',
            'urlLinks',
        ]:
            if not getattr(self, attr, None):
                setattr(self, attr, [])
Rob Carleski's avatar
V2    
Rob Carleski committed
235
236
237

    def create(self):
        """Create a new mcommunity group
Rob Carleski's avatar
Rob Carleski committed
238
239
240

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
241
        None
Rob Carleski's avatar
Rob Carleski committed
242
243
244

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
245
        None
Rob Carleski's avatar
Rob Carleski committed
246
        """
Rob Carleski's avatar
V2    
Rob Carleski committed
247
248
249
250
251
252
253
254
255

        core.validate_name(self.client, self.name)

        # Testing shows that this is a black hole.
        # We should expect this to time out, and move on.
        try:
            self.client.post(
                url='/create',
                data=json.dumps({'name': self.name}),
256
            )
Rob Carleski's avatar
V2    
Rob Carleski committed
257
258
        except Timeout:
            pass
Rob Carleski's avatar
Rob Carleski committed
259

Rob Carleski's avatar
V2    
Rob Carleski committed
260
261
262
263
264
        self.fetch()
        return self

    def delete(self):
        """Delete an mcommunity group
Rob Carleski's avatar
Rob Carleski committed
265
266
267

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
268
        None
Rob Carleski's avatar
Rob Carleski committed
269
270
271
272
273
274

        Returns
        -------
        None
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
275
276
277
        r = self.client.get(
            url='/delete/{}'.format(quote(self.dn))
        )
Rob Carleski's avatar
Rob Carleski committed
278

Rob Carleski's avatar
V2    
Rob Carleski committed
279
280
281
282
283
284
285
        if r.ok:
            self.fetch()
        else:
            raise core.MCommError('{}: {}'.format(r.status_code, r.text))

    def renew(self):
        """Renew an mcommunity group
Rob Carleski's avatar
Rob Carleski committed
286
287
288

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
289
        None
Rob Carleski's avatar
Rob Carleski committed
290
291
292

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
293
        None
Rob Carleski's avatar
Rob Carleski committed
294
        """
Rob Carleski's avatar
V2    
Rob Carleski committed
295
296
297

        r = self.client.get(
            url='/renew/{}'.format(quote(self.dn))
Rob Carleski's avatar
Rob Carleski committed
298
299
        )

Rob Carleski's avatar
V2    
Rob Carleski committed
300
301
        if r.ok:
            self.fetch()
Rob Carleski's avatar
Rob Carleski committed
302
        else:
Rob Carleski's avatar
V2    
Rob Carleski committed
303
            raise core.MCommError('{}: {}'.format(r.status_code, r.text))
Rob Carleski's avatar
Rob Carleski committed
304

Rob Carleski's avatar
V2    
Rob Carleski committed
305
306
    def reserve(self):
        """Reserve a new mcommunity group
Rob Carleski's avatar
Rob Carleski committed
307
308
309

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
310
        None
Rob Carleski's avatar
Rob Carleski committed
311
312
313

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
314
        None
Rob Carleski's avatar
Rob Carleski committed
315
316
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
317
318
319
320
321
322
323
324
325
326
327
        core.validate_name(self.client, self.name)
        # Testing shows that this is a black hole.
        # We should expect this to time out, and move on.
        try:
            self.client.post(
                url='/reserve',
                data=json.dumps({'name': self.name}),
                timeout=5
            )
        except Timeout:
            pass
Rob Carleski's avatar
Rob Carleski committed
328

Rob Carleski's avatar
V2    
Rob Carleski committed
329
330
331
332
333
        self.fetch()
        return self

    def update_aliases(self):
        """Update mcommunity group aliases
Rob Carleski's avatar
Rob Carleski committed
334
335
336

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
337
        None
Rob Carleski's avatar
Rob Carleski committed
338
339
340

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
341
        None
Rob Carleski's avatar
Rob Carleski committed
342
343
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
344
345
346
347
348
349
        r = self.client.post(
            url='/update/aliases',
            data=json.dumps({
                'dn': self.dn,
                'aliases': self.aliases
            })
Rob Carleski's avatar
Rob Carleski committed
350
        )
Rob Carleski's avatar
V2    
Rob Carleski committed
351
352
        if r.ok:
            self.fetch(['aliases'])
Rob Carleski's avatar
Rob Carleski committed
353
        else:
Rob Carleski's avatar
V2    
Rob Carleski committed
354
            raise core.MCommError('{}: {}'.format(r.status_code, r.text))
Rob Carleski's avatar
Rob Carleski committed
355

Rob Carleski's avatar
V2    
Rob Carleski committed
356
357
    def update_description(self):
        """Update mcommunity group description
Rob Carleski's avatar
Rob Carleski committed
358
359
360

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
361
        None
Rob Carleski's avatar
Rob Carleski committed
362
363
364

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
365
        None
Rob Carleski's avatar
Rob Carleski committed
366
367
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
368
369
370
371
372
373
374
375
376
377
378
379
380
381
        _valid_levels = ['PUBLIC', 'PROTECTED', 'PRIVATE']
        if self.descriptionLevel.upper() not in _valid_levels:
            raise core.MCommError('Invalid description level. Valid options '
                                  'are PUBLIC, PROTECTED, and PRIVATE.')
        r = self.client.post(
            url='/update/description',
            data=json.dumps({
                'dn': self.dn,
                'description': self.description,
                'descriptionLevel': self.descriptionLevel.upper()
            })
        )
        if r.ok:
            self.fetch(['description', 'descriptionLevel'])
Rob Carleski's avatar
Rob Carleski committed
382
        else:
Rob Carleski's avatar
V2    
Rob Carleski committed
383
            raise core.MCommError('{}: {}'.format(r.status_code, r.text))
Rob Carleski's avatar
Rob Carleski committed
384

Rob Carleski's avatar
V2    
Rob Carleski committed
385
386
387
388
    def update_errors_to(self):
        """Update mcommunity errorsTo

        Uniqnames or dn/cns can be appeneded to self.errorsTo
389
390
391

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
392
        None
393
394
395

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
396
        None
397
398
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
399
        for item in self.errorsTo:
400
            try:
Rob Carleski's avatar
V2    
Rob Carleski committed
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
                parse_dn(item)
            except LDAPInvalidDnError:
                _index = self.errorsTo.index(item)
                dn = core.get_entity_dn(self.client, item)
                self.errorsTo[_index] = dn

        r = self.client.post(
            url='/update/errorsTo',
            data=json.dumps({
                'dn': self.dn,
                'errorsTo': self.errorsTo
            })
        )
        if r.ok:
            self.fetch(['errorsTo'])
416
        else:
Rob Carleski's avatar
V2    
Rob Carleski committed
417
            raise core.MCommError('{}: {}'.format(r.status_code, r.text))
418

Rob Carleski's avatar
V2    
Rob Carleski committed
419
420
    def update_errors_to_external(self):
        """Update mcommunity errorsToExternal
Rob Carleski's avatar
Rob Carleski committed
421

Rob Carleski's avatar
V2    
Rob Carleski committed
422
423
424
425
426
        Addresses can be added to self.errorsToExternal in these formats:

        str : user@domain.tld
        str : Test User <user@domain.tld>
        dict : {'name': 'Test User', 'email': 'user@domain.tld'}
Rob Carleski's avatar
Rob Carleski committed
427
428
429

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
430
        None
Rob Carleski's avatar
Rob Carleski committed
431
432
433

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
434
        None
Rob Carleski's avatar
Rob Carleski committed
435
436
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
        for item in self.errorsToExternal:
            if not isinstance(item, dict):
                _index = self.errorsToExternal.index(item)
                self.errorsToExternal[_index] = {'email': item}

        r = self.client.post(
            url='/update/errorsToExternalMember',
            data=json.dumps({
                'dn': self.dn,
                'errorsToExternal': self.errorsToExternal
            })
        )
        if r.ok:
            self.fetch(['errorsToExternal', 'errorsToExternalRaw'])
        else:
            raise core.MCommError('{}: {}'.format(r.status_code, r.text))
Rob Carleski's avatar
Rob Carleski committed
453

Rob Carleski's avatar
V2    
Rob Carleski committed
454
455
    def update_external_members(self):
        """Update mcommunity group external members
Rob Carleski's avatar
Rob Carleski committed
456

Rob Carleski's avatar
V2    
Rob Carleski committed
457
        External members can be added to self.externalMembers in these formats:
Rob Carleski's avatar
Rob Carleski committed
458

Rob Carleski's avatar
V2    
Rob Carleski committed
459
460
461
        str : user@domain.tld
        str : Test User <user@domain.tld>
        dict : {'name': 'Test User', 'email': 'user@domain.tld'}
Rob Carleski's avatar
Rob Carleski committed
462
463
464

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
465
        None
Rob Carleski's avatar
Rob Carleski committed
466
467
468

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
469
        None
Rob Carleski's avatar
Rob Carleski committed
470
471
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
        self.memberExternal = []
        for member in self.externalMembers:
            if isinstance(member, dict):
                self.memberExternal.append(member)
            else:
                self.memberExternal.append({'email': member})

        r = self.client.post(
            url='/update/externalMember',
            data=json.dumps({
                'dn': self.dn,
                'memberExternal': self.memberExternal
            })
        )
        if r.ok:
            del(self._externalMembers)
            self.fetch(['memberExternal', 'memberExternalRaw'])
        else:
            raise core.MCommError('{}: {}'.format(r.status_code, r.text))

    def update_links(self):
        """Update mcommunity group external links

        Links can be added to self.links in these formats:
        str : https://www.google.com
        str : Google https://www.google.com
        str : https://www.google.com Google
        dict: {'urlName' : 'Google', 'urlValue': 'https://www.google.com'}
Rob Carleski's avatar
Rob Carleski committed
500
501
502

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
503
        None
Rob Carleski's avatar
Rob Carleski committed
504
505
506

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
507
        None
Rob Carleski's avatar
Rob Carleski committed
508
509
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
        self.urlLinks = []
        for item in self.links:
            if isinstance(item, dict):
                link = '{} {}'.format(
                    item['urlValue'],
                    item['urlName']
                )
            elif ' ' in item:
                _split = item.split(' ')
                for part in _split:
                    if 'http:' in part or 'https:' in part:
                        _url = _split.pop(_split.index(part))
                        break
                link = '{} {}'.format(_url, ' '.join(_split))
                _url = ''
            else:
                link = item

            self.urlLinks.append({'labeledUri': link})

        r = self.client.post(
            url='/update/links',
            data=json.dumps({
                'dn': self.dn,
                'urlLinks': self.urlLinks
            })
        )
        if r.ok:
            del(self._links)
            self.fetch(['urlLinks', 'labeledUri'])
        else:
            raise core.MCommError('{}: {}'.format(r.status_code, r.text))

    def update_membership(self):
        """Shortcut for updating all membership types at onces
Rob Carleski's avatar
Rob Carleski committed
545
546
547

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
548
        None
Rob Carleski's avatar
Rob Carleski committed
549
550
551

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
552
        None
Rob Carleski's avatar
Rob Carleski committed
553
        """
554
        if self.memberDn or self.members:
555
            self.members
556
557
            self.update_members()
        if self.memberGroupDn or self.memberGroups:
558
            self.memberGroups
559
560
            self.update_member_groups()
        if self.memberExternal or self.externalMembers:
561
            self.externalMembers
562
            self.update_external_members()
Rob Carleski's avatar
Rob Carleski committed
563

Rob Carleski's avatar
V2    
Rob Carleski committed
564
565
566
567
568
    def update_members(self):
        """Update members of an mcommunity group.

        Group members should be added to self.members by uniqname.
        However, using an ldap string should work, too.
Rob Carleski's avatar
Rob Carleski committed
569
570
571

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
572
        None
Rob Carleski's avatar
Rob Carleski committed
573
574
575

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
576
        None
Rob Carleski's avatar
Rob Carleski committed
577
        """
578

Rob Carleski's avatar
V2    
Rob Carleski committed
579
580
581
582
583
584
585
        self.memberDn = []
        for member in self.members:
            self.memberDn.append(core.get_entity_dn(
                self.client,
                member
                )
            )
Rob Carleski's avatar
Rob Carleski committed
586

Rob Carleski's avatar
V2    
Rob Carleski committed
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
        r = self.client.post(
            url='/update/member',
            data=json.dumps({
                'dn': self.dn,
                'memberDn': self.memberDn
            })
        )
        if r.ok:
            del(self._members)
            self.fetch(['memberDn'])
        else:
            raise core.MCommError('{}: {}'.format(r.status_code, r.text))

    def update_member_groups(self):
        """Update member groups of an mcommunity group.
Rob Carleski's avatar
Rob Carleski committed
602

Rob Carleski's avatar
V2    
Rob Carleski committed
603
604
        Groups can be added to self.memberGroups by dn or cn.
        However, full ldap strings should work here as well.
Rob Carleski's avatar
Rob Carleski committed
605
606
607

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
608
        None
Rob Carleski's avatar
Rob Carleski committed
609
610
611

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
612
        None
Rob Carleski's avatar
Rob Carleski committed
613
614
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
615
616
617
618
619
        self.memberGroupDn = []
        for member in self.memberGroups:
            self.memberGroupDn.append(core.get_entity_dn(
                self.client,
                member
Rob Carleski's avatar
Rob Carleski committed
620
                )
Rob Carleski's avatar
V2    
Rob Carleski committed
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
            )
        r = self.client.post(
            url='/update/groupMember',
            data=json.dumps({
                'dn': self.dn,
                'memberGroupDn': self.memberGroupDn
            })
        )
        if r.ok:
            del(self._memberGroups)
            if hasattr(self, '_expandedMembers'):
                del(self._expandedMembers)
            self.fetch(['memberGroupDn', 'groupMemberDnRaw'])
        else:
            raise core.MCommError('{}: {}'.format(r.status_code, r.text))
Rob Carleski's avatar
Rob Carleski committed
636

Rob Carleski's avatar
V2    
Rob Carleski committed
637
638
639
640
    def update_moderators(self):
        """Update mcommunity group moderators

        Moderators can be added to self.externalMembers in these formats:
Rob Carleski's avatar
Rob Carleski committed
641

Rob Carleski's avatar
V2    
Rob Carleski committed
642
643
644
        str : user@domain.tld
        str : Test User <user@domain.tld>
        dict : {'name': 'Test User', 'email': 'user@domain.tld'}
Rob Carleski's avatar
Rob Carleski committed
645
646
647

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
648
        None
Rob Carleski's avatar
Rob Carleski committed
649
650
651

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
652
        None
Rob Carleski's avatar
Rob Carleski committed
653
654
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
        self.moderator = []
        for mod in self.moderators:
            if isinstance(mod, dict):
                self.moderator.append(mod)
            else:
                self.moderator.append({'email': mod})

        r = self.client.post(
            url='/update/moderator',
            data=json.dumps({
                'dn': self.dn,
                'moderator': self.moderator
            })
        )

        if r.ok:
            del(self._moderators)
            self.fetch(['moderator', 'moderatorRaw'])
        else:
            raise core.MCommError('{}: {}'.format(r.status_code, r.text))
Rob Carleski's avatar
Rob Carleski committed
675

Rob Carleski's avatar
V2    
Rob Carleski committed
676
677
    def update_notice(self):
        """Update mcommunity group notice
Rob Carleski's avatar
Rob Carleski committed
678

Rob Carleski's avatar
V2    
Rob Carleski committed
679
680
681
        Parameters
        ----------
        None
Rob Carleski's avatar
Rob Carleski committed
682

Rob Carleski's avatar
V2    
Rob Carleski committed
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
        Returns
        -------
        Notice
        """

        _valid_levels = ['PUBLIC', 'PROTECTED', 'PRIVATE']
        if self.noticeLevel.upper() not in _valid_levels:
            raise core.MCommError('Invalid notice level. Valid options are '
                                  'PUBLIC, PROTECTED, and PRIVATE.')

        r = self.client.post(
            url='/update/notice',
            data=json.dumps({
                'dn': self.dn,
                'notice': self.notice,
                'noticeLevel': self.noticeLevel.upper()
            })
        )
        if r.ok:
            self.fetch(['notice', 'noticeLevel'])
        else:
            raise core.MCommError('{}: {}'.format(r.status_code, r.text))

    def update_ownership(self):
        """Alias function for update_owners
Rob Carleski's avatar
Rob Carleski committed
708
709
710

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
711
        None
Rob Carleski's avatar
Rob Carleski committed
712
713
714

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
715
        None
Rob Carleski's avatar
Rob Carleski committed
716
717
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
718
        self.update_owners()
Rob Carleski's avatar
Rob Carleski committed
719

Rob Carleski's avatar
V2    
Rob Carleski committed
720
721
    def update_owners(self):
        """Update owners of an mcommunity group.
Rob Carleski's avatar
Rob Carleski committed
722
723
724

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
725
        None
Rob Carleski's avatar
Rob Carleski committed
726
727
728

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
729
        None
Rob Carleski's avatar
Rob Carleski committed
730
731
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
732
733
734
735
736
        self.ownerDn = []
        for owner in self.owners:
            self.ownerDn.append(core.get_entity_dn(
                self.client,
                owner
737
                )
Rob Carleski's avatar
V2    
Rob Carleski committed
738
739
740
741
742
743
744
745
746
747
748
749
750
751
            )

        r = self.client.post(
            url='/update/owner',
            data=json.dumps({
                'dn': self.dn,
                'ownerDn': self.ownerDn
            })
        )
        if r.ok:
            del(self._owners)
            self.fetch(['ownerDn', 'owners_details'])
        else:
            raise core.MCommError('{}: {}'.format(r.status_code, r.text))
Rob Carleski's avatar
Rob Carleski committed
752

Rob Carleski's avatar
V2    
Rob Carleski committed
753
754
755
756
    def update_request_to(self):
        """Update mcommunity requestTo

        Uniqnames or dn/cns can be appeneded to self.requestTo
Rob Carleski's avatar
Rob Carleski committed
757
758
759

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
760
        None
Rob Carleski's avatar
Rob Carleski committed
761
762
763

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
764
        None
Rob Carleski's avatar
Rob Carleski committed
765
766
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
767
        for item in self.requestTo:
Rob Carleski's avatar
Rob Carleski committed
768
            try:
Rob Carleski's avatar
V2    
Rob Carleski committed
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
                parse_dn(item)
            except LDAPInvalidDnError:
                _index = self.requestTo.index(item)
                dn = core.get_entity_dn(self.client, item)
                self.requestTo[_index] = dn

        r = self.client.post(
            url='/update/requestTo',
            data=json.dumps({
                'dn': self.dn,
                'requestTo': self.requestTo
            })
        )
        if r.ok:
            self.fetch(['requestTo'])
        else:
            raise core.MCommError('{}: {}'.format(r.status_code, r.text))

    def update_request_to_external(self):
        """Update mcommunity requestToExternal
Rob Carleski's avatar
Rob Carleski committed
789

Rob Carleski's avatar
V2    
Rob Carleski committed
790
791
792
793
794
        Addresses can be added to self.requestToExternal in these formats:

        str : user@domain.tld
        str : Test User <user@domain.tld>
        dict : {'name': 'Test User', 'email': 'user@domain.tld'}
Rob Carleski's avatar
Rob Carleski committed
795
796
797

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
798
            none
Rob Carleski's avatar
Rob Carleski committed
799
800
801
802
803
804
805

        Returns
        -------
        dict
            A dict of response information from the server.
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
        for item in self.requestToExternal:
            if not isinstance(item, dict):
                _index = self.requestToExternal.index(item)
                self.requestToExternal[_index] = {'email': item}

        r = self.client.post(
            url='/update/requestToExternalMember',
            data=json.dumps({
                'dn': self.dn,
                'requestToExternal': self.requestToExternal
            })
        )
        if r.ok:
            self.fetch(['requestToExternal', 'requestToExternalRaw'])
        else:
            raise core.MCommError('{}: {}'.format(r.status_code, r.text))

    def update_settings(self):
Rob Carleski's avatar
Rob Carleski committed
824
        """Generic endpoint for updating the following settings:
Rob Carleski's avatar
V2    
Rob Carleski committed
825
826
            - isPrivate
            - isJoinable
Rob Carleski's avatar
Rob Carleski committed
827
828
            - IsSpamBlocked
            - IsEmailableByMembersOnly
Rob Carleski's avatar
V2    
Rob Carleski committed
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
            - IsEmailWarningSuppressed

        Parameters
        ----------
        None

        Returns
        -------
        None
        """

        r = self.client.post(
            url='/update/settings',
            data=json.dumps({
                'dn': self.dn,
                'isPrivate': self.isPrivate,
                'isJoinable': self.isJoinable,
                'isSpamBlocked': self.isSpamBlocked,
                'isEmailableByMembersOnly': self.isEmailableByMembersOnly,
                'isEmailWarningSuppressed': self.isEmailWarningSuppressed
            })
        )
        if r.ok:
            self.fetch([
                'isPrivate',
                'isJoinable',
                'isSpamBlocked',
                'isEmailableByMembersOnly',
                'isEmailWarningSuppressed'
            ])
        else:
            raise core.MCommError('{}: {}'.format(r.status_code, r.text))


class MCommPerson:
Rob Carleski's avatar
Rob Carleski committed
864

Rob Carleski's avatar
V2    
Rob Carleski committed
865
866
867
868
869
870
871
    def __init__(self, client, uniqname):
        self.client = client
        self.uniqname = uniqname
        self.fetch()

    def fetch(self):
        """Fetch information about a user from mcommunity
Rob Carleski's avatar
Rob Carleski committed
872
873
874

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
875
        None
Rob Carleski's avatar
Rob Carleski committed
876
877
878

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
879
        None
Rob Carleski's avatar
Rob Carleski committed
880
        """
Rob Carleski's avatar
V2    
Rob Carleski committed
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
        r = self.client.get(
            url='/find/person/{}'.format(self.uniqname)
        )

        # The API returns a 200 here no matter what.
        # The best way to determine if there's data is
        # probably to just check the dumped text response.
        if r.text:
            self.__dict__.update(r.json())
        else:
            raise core.MCommError('No matching user found')


class MCommClient:

    def __init__(self, client_id, secret):
        self.client = MCommSession(client_id, secret)

    def group(self, groupname):
        return MCommGroup(self.client, groupname)

    def person(self, uniqname):
        return MCommPerson(self.client, uniqname)