mcommunity.py 23.5 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
171

        self.dn = core.get_entity_dn(self.client, self.name)
172
173
174
175
176
177
178
179
180
181
182
183
184
185

        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(
186
                        r.status_code,
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
                        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
212
                    )
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
                )

        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
232
233
234

    def create(self):
        """Create a new mcommunity group
Rob Carleski's avatar
Rob Carleski committed
235
236
237

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
238
        None
Rob Carleski's avatar
Rob Carleski committed
239
240
241

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
242
        None
Rob Carleski's avatar
Rob Carleski committed
243
        """
Rob Carleski's avatar
V2    
Rob Carleski committed
244
245
246
247
248
249
250
251
252

        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}),
253
            )
Rob Carleski's avatar
V2    
Rob Carleski committed
254
255
        except Timeout:
            pass
Rob Carleski's avatar
Rob Carleski committed
256

Rob Carleski's avatar
V2    
Rob Carleski committed
257
258
259
260
261
        self.fetch()
        return self

    def delete(self):
        """Delete an mcommunity group
Rob Carleski's avatar
Rob Carleski committed
262
263
264

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
265
        None
Rob Carleski's avatar
Rob Carleski committed
266
267
268
269
270
271

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

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

Rob Carleski's avatar
V2    
Rob Carleski committed
276
277
278
279
280
281
282
        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
283
284
285

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
286
        None
Rob Carleski's avatar
Rob Carleski committed
287
288
289

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
290
        None
Rob Carleski's avatar
Rob Carleski committed
291
        """
Rob Carleski's avatar
V2    
Rob Carleski committed
292
293
294

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

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

Rob Carleski's avatar
V2    
Rob Carleski committed
302
303
    def reserve(self):
        """Reserve a new mcommunity group
Rob Carleski's avatar
Rob Carleski committed
304
305
306

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
307
        None
Rob Carleski's avatar
Rob Carleski committed
308
309
310

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
311
        None
Rob Carleski's avatar
Rob Carleski committed
312
313
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
314
315
316
317
318
319
320
321
322
323
324
        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
325

Rob Carleski's avatar
V2    
Rob Carleski committed
326
327
328
329
330
        self.fetch()
        return self

    def update_aliases(self):
        """Update mcommunity group aliases
Rob Carleski's avatar
Rob Carleski committed
331
332
333

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
334
        None
Rob Carleski's avatar
Rob Carleski committed
335
336
337

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
338
        None
Rob Carleski's avatar
Rob Carleski committed
339
340
        """

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

Rob Carleski's avatar
V2    
Rob Carleski committed
353
354
    def update_description(self):
        """Update mcommunity group description
Rob Carleski's avatar
Rob Carleski committed
355
356
357

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
358
        None
Rob Carleski's avatar
Rob Carleski committed
359
360
361

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
362
        None
Rob Carleski's avatar
Rob Carleski committed
363
364
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
365
366
367
368
369
370
371
372
373
374
375
376
377
378
        _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
379
        else:
Rob Carleski's avatar
V2    
Rob Carleski committed
380
            raise core.MCommError('{}: {}'.format(r.status_code, r.text))
Rob Carleski's avatar
Rob Carleski committed
381

Rob Carleski's avatar
V2    
Rob Carleski committed
382
383
384
385
    def update_errors_to(self):
        """Update mcommunity errorsTo

        Uniqnames or dn/cns can be appeneded to self.errorsTo
386
387
388

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
389
        None
390
391
392

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
393
        None
394
395
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
396
        for item in self.errorsTo:
397
            try:
Rob Carleski's avatar
V2    
Rob Carleski committed
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
                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'])
413
        else:
Rob Carleski's avatar
V2    
Rob Carleski committed
414
            raise core.MCommError('{}: {}'.format(r.status_code, r.text))
415

Rob Carleski's avatar
V2    
Rob Carleski committed
416
417
    def update_errors_to_external(self):
        """Update mcommunity errorsToExternal
Rob Carleski's avatar
Rob Carleski committed
418

Rob Carleski's avatar
V2    
Rob Carleski committed
419
420
421
422
423
        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
424
425
426

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
427
        None
Rob Carleski's avatar
Rob Carleski committed
428
429
430

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
431
        None
Rob Carleski's avatar
Rob Carleski committed
432
433
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
        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
450

Rob Carleski's avatar
V2    
Rob Carleski committed
451
452
    def update_external_members(self):
        """Update mcommunity group external members
Rob Carleski's avatar
Rob Carleski committed
453

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

Rob Carleski's avatar
V2    
Rob Carleski committed
456
457
458
        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
459
460
461

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
462
        None
Rob Carleski's avatar
Rob Carleski committed
463
464
465

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
466
        None
Rob Carleski's avatar
Rob Carleski committed
467
468
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
469
470
471
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
        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
497
498
499

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
500
        None
Rob Carleski's avatar
Rob Carleski committed
501
502
503

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
504
        None
Rob Carleski's avatar
Rob Carleski committed
505
506
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
507
508
509
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
        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
542
543
544

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
545
        None
Rob Carleski's avatar
Rob Carleski committed
546
547
548

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

Rob Carleski's avatar
V2    
Rob Carleski committed
561
562
563
564
565
    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
566
567
568

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
569
        None
Rob Carleski's avatar
Rob Carleski committed
570
571
572

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
573
        None
Rob Carleski's avatar
Rob Carleski committed
574
        """
575

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

Rob Carleski's avatar
V2    
Rob Carleski committed
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
        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
599

Rob Carleski's avatar
V2    
Rob Carleski committed
600
601
        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
602
603
604

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
605
        None
Rob Carleski's avatar
Rob Carleski committed
606
607
608

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
609
        None
Rob Carleski's avatar
Rob Carleski committed
610
611
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
612
613
614
615
616
        self.memberGroupDn = []
        for member in self.memberGroups:
            self.memberGroupDn.append(core.get_entity_dn(
                self.client,
                member
Rob Carleski's avatar
Rob Carleski committed
617
                )
Rob Carleski's avatar
V2    
Rob Carleski committed
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
            )
        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
633

Rob Carleski's avatar
V2    
Rob Carleski committed
634
635
636
637
    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
638

Rob Carleski's avatar
V2    
Rob Carleski committed
639
640
641
        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
642
643
644

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
645
        None
Rob Carleski's avatar
Rob Carleski committed
646
647
648

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
649
        None
Rob Carleski's avatar
Rob Carleski committed
650
651
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
        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
672

Rob Carleski's avatar
V2    
Rob Carleski committed
673
674
    def update_notice(self):
        """Update mcommunity group notice
Rob Carleski's avatar
Rob Carleski committed
675

Rob Carleski's avatar
V2    
Rob Carleski committed
676
677
678
        Parameters
        ----------
        None
Rob Carleski's avatar
Rob Carleski committed
679

Rob Carleski's avatar
V2    
Rob Carleski committed
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
        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
705
706
707

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
708
        None
Rob Carleski's avatar
Rob Carleski committed
709
710
711

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
712
        None
Rob Carleski's avatar
Rob Carleski committed
713
714
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
715
        self.update_owners()
Rob Carleski's avatar
Rob Carleski committed
716

Rob Carleski's avatar
V2    
Rob Carleski committed
717
718
    def update_owners(self):
        """Update owners of an mcommunity group.
Rob Carleski's avatar
Rob Carleski committed
719
720
721

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
722
        None
Rob Carleski's avatar
Rob Carleski committed
723
724
725

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
726
        None
Rob Carleski's avatar
Rob Carleski committed
727
728
        """

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

        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
749

Rob Carleski's avatar
V2    
Rob Carleski committed
750
751
752
753
    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
754
755
756

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
757
        None
Rob Carleski's avatar
Rob Carleski committed
758
759
760

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
761
        None
Rob Carleski's avatar
Rob Carleski committed
762
763
        """

Rob Carleski's avatar
V2    
Rob Carleski committed
764
        for item in self.requestTo:
Rob Carleski's avatar
Rob Carleski committed
765
            try:
Rob Carleski's avatar
V2    
Rob Carleski committed
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
                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
786

Rob Carleski's avatar
V2    
Rob Carleski committed
787
788
789
790
791
        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
792
793
794

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
795
            none
Rob Carleski's avatar
Rob Carleski committed
796
797
798
799
800
801
802

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

Rob Carleski's avatar
V2    
Rob Carleski committed
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
        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
821
        """Generic endpoint for updating the following settings:
Rob Carleski's avatar
V2    
Rob Carleski committed
822
823
            - isPrivate
            - isJoinable
Rob Carleski's avatar
Rob Carleski committed
824
825
            - IsSpamBlocked
            - IsEmailableByMembersOnly
Rob Carleski's avatar
V2    
Rob Carleski committed
826
827
828
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
            - 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
861

Rob Carleski's avatar
V2    
Rob Carleski committed
862
863
864
865
866
867
868
    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
869
870
871

        Parameters
        ----------
Rob Carleski's avatar
V2    
Rob Carleski committed
872
        None
Rob Carleski's avatar
Rob Carleski committed
873
874
875

        Returns
        -------
Rob Carleski's avatar
V2    
Rob Carleski committed
876
        None
Rob Carleski's avatar
Rob Carleski committed
877
        """
Rob Carleski's avatar
V2    
Rob Carleski committed
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
        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)