models.py 38 KB
Newer Older
Antony Chazapis's avatar
Antony Chazapis committed
1
# Copyright 2011-2012 GRNET S.A. All rights reserved.
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
2
#
3
4
5
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
6
#
7
8
9
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
10
#
11
12
13
14
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
15
#
16
17
18
19
20
21
22
23
24
25
26
27
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
28
#
29
30
31
32
33
34
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

import hashlib
35
import uuid
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
36
import logging
37
38
39
40

from time import asctime
from datetime import datetime, timedelta
from base64 import b64encode
41
from urlparse import urlparse
42
from urllib import quote
43
from random import randint
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
44
from collections import defaultdict
45

46
from django.db import models, IntegrityError
Olga Brani's avatar
Olga Brani committed
47
from django.contrib.auth.models import User, UserManager, Group, Permission
48
from django.utils.translation import ugettext as _
49
from django.db import transaction
50
from django.core.exceptions import ValidationError
51
52
53
from django.db.models.signals import (
    pre_save, post_save, post_syncdb, post_delete
)
Olga Brani's avatar
Olga Brani committed
54
55
from django.contrib.contenttypes.models import ContentType

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
56
from django.dispatch import Signal
57
from django.db.models import Q
58
59
60
from django.core.urlresolvers import reverse
from django.utils.http import int_to_base36
from django.contrib.auth.tokens import default_token_generator
61
from django.conf import settings
62
from django.utils.importlib import import_module
63
from django.core.validators import email_re
64

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
65
from astakos.im.settings import (DEFAULT_USER_LEVEL, INVITATIONS_PER_LEVEL,
66
67
                                 AUTH_TOKEN_DURATION, BILLING_FIELDS,
                                 EMAILCHANGE_ACTIVATION_DAYS, LOGGING_LEVEL)
68
69
from astakos.im.endpoints.qh import (
    register_users, send_quota, register_resources
70
)
71
from astakos.im import auth_providers
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
72
from astakos.im.endpoints.aquarium.producer import report_user_event
Olga Brani's avatar
Olga Brani committed
73
from astakos.im.functions import send_invitation
root's avatar
root committed
74
#from astakos.im.tasks import propagate_groupmembers_quota
75

Olga Brani's avatar
Olga Brani committed
76
import astakos.im.messages as astakos_messages
77

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
78
79
logger = logging.getLogger(__name__)

Olga Brani's avatar
Olga Brani committed
80
81
82
83
84
85
86
87
DEFAULT_CONTENT_TYPE = None
try:
    content_type = ContentType.objects.get(app_label='im', model='astakosuser')
except:
    content_type = DEFAULT_CONTENT_TYPE

RESOURCE_SEPARATOR = '.'

88
inf = float('inf')
89

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
90
91
92
93
94
95
96
class Service(models.Model):
    name = models.CharField('Name', max_length=255, unique=True, db_index=True)
    url = models.FilePathField()
    icon = models.FilePathField(blank=True)
    auth_token = models.CharField('Authentication Token', max_length=32,
                                  null=True, blank=True)
    auth_token_created = models.DateTimeField('Token creation date', null=True)
97
98
99
    auth_token_expires = models.DateTimeField(
        'Token expiration date', null=True)

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
100
101
102
103
104
105
106
107
108
    def renew_token(self):
        md5 = hashlib.md5()
        md5.update(self.name.encode('ascii', 'ignore'))
        md5.update(self.url.encode('ascii', 'ignore'))
        md5.update(asctime())

        self.auth_token = b64encode(md5.digest())
        self.auth_token_created = datetime.now()
        self.auth_token_expires = self.auth_token_created + \
109
110
            timedelta(hours=AUTH_TOKEN_DURATION)

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
111
112
113
    def __str__(self):
        return self.name

Olga Brani's avatar
Olga Brani committed
114
115
116
117
118
119
120
121
    @property
    def resources(self):
        return self.resource_set.all()

    @resources.setter
    def resources(self, resources):
        for s in resources:
            self.resource_set.create(**s)
122

Olga Brani's avatar
Olga Brani committed
123
124
125
126
127
128
129
130
131
132
133
    def add_resource(self, service, resource, uplimit, update=True):
        """Raises ObjectDoesNotExist, IntegrityError"""
        resource = Resource.objects.get(service__name=service, name=resource)
        if update:
            AstakosUserQuota.objects.update_or_create(user=self,
                                                      resource=resource,
                                                      defaults={'uplimit': uplimit})
        else:
            q = self.astakosuserquota_set
            q.create(resource=resource, uplimit=uplimit)

134

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
135
136
137
138
class ResourceMetadata(models.Model):
    key = models.CharField('Name', max_length=255, unique=True, db_index=True)
    value = models.CharField('Value', max_length=255)

139

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
140
141
142
143
class Resource(models.Model):
    name = models.CharField('Name', max_length=255, unique=True, db_index=True)
    meta = models.ManyToManyField(ResourceMetadata)
    service = models.ForeignKey(Service)
Olga Brani's avatar
Olga Brani committed
144
145
146
    desc = models.TextField('Description', null=True)
    unit = models.CharField('Name', null=True, max_length=255)
    group = models.CharField('Group', null=True, max_length=255)
147

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
148
    def __str__(self):
Olga Brani's avatar
Olga Brani committed
149
        return '%s%s%s' % (self.service, RESOURCE_SEPARATOR, self.name)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
150

151

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
152
153
class GroupKind(models.Model):
    name = models.CharField('Name', max_length=255, unique=True, db_index=True)
154

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
155
156
157
    def __str__(self):
        return self.name

158

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
159
160
class AstakosGroup(Group):
    kind = models.ForeignKey(GroupKind)
161
162
    homepage = models.URLField(
        'Homepage Url', max_length=255, null=True, blank=True)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
163
    desc = models.TextField('Description', null=True)
Olga Brani's avatar
Olga Brani committed
164
165
166
167
168
169
170
171
172
173
    policy = models.ManyToManyField(
        Resource,
        null=True,
        blank=True,
        through='AstakosGroupQuota'
    )
    creation_date = models.DateTimeField(
        'Creation date',
        default=datetime.now()
    )
Olga Brani's avatar
Olga Brani committed
174
    issue_date = models.DateTimeField('Start date', null=True)
Olga Brani's avatar
Olga Brani committed
175
    expiration_date = models.DateTimeField(
Olga Brani's avatar
Olga Brani committed
176
        'End date',
Olga Brani's avatar
Olga Brani committed
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
         null=True
    )
    moderation_enabled = models.BooleanField(
        'Moderated membership?',
        default=True
    )
    approval_date = models.DateTimeField(
        'Activation date',
        null=True,
        blank=True
    )
    estimated_participants = models.PositiveIntegerField(
        'Estimated #members',
        null=True,
        blank=True,
    )
    max_participants = models.PositiveIntegerField(
        'Maximum numder of participants',
        null=True,
        blank=True
    )
198

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
199
200
    @property
    def is_disabled(self):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
201
202
203
        if not self.approval_date:
            return True
        return False
204

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
205
    @property
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
206
    def is_enabled(self):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
207
208
209
210
211
212
213
214
215
216
217
218
        if self.is_disabled:
            return False
        if not self.issue_date:
            return False
        if not self.expiration_date:
            return True
        now = datetime.now()
        if self.issue_date > now:
            return False
        if now >= self.expiration_date:
            return False
        return True
219

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
220
    def enable(self):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
221
222
        if self.is_enabled:
            return
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
223
224
        self.approval_date = datetime.now()
        self.save()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
225
        quota_disturbed.send(sender=self, users=self.approved_members)
root's avatar
root committed
226
227
228
229
        #propagate_groupmembers_quota.apply_async(
        #    args=[self], eta=self.issue_date)
        #propagate_groupmembers_quota.apply_async(
        #    args=[self], eta=self.expiration_date)
230

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
231
    def disable(self):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
232
233
        if self.is_disabled:
            return
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
234
235
        self.approval_date = None
        self.save()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
236
        quota_disturbed.send(sender=self, users=self.approved_members)
237

Olga Brani's avatar
Olga Brani committed
238
    @transaction.commit_manually
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
239
    def approve_member(self, person):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
240
        m, created = self.membership_set.get_or_create(person=person)
Olga Brani's avatar
Olga Brani committed
241
        try:
242
            m.approve()
Olga Brani's avatar
Olga Brani committed
243
244
245
246
247
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()
248

Olga Brani's avatar
Olga Brani committed
249
250
#     def disapprove_member(self, person):
#         self.membership_set.remove(person=person)
251

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
252
253
    @property
    def members(self):
254
255
        q = self.membership_set.select_related().all()
        return [m.person for m in q]
256

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
257
258
    @property
    def approved_members(self):
259
260
        q = self.membership_set.select_related().all()
        return [m.person for m in q if m.is_approved]
261

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
262
    @property
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
263
    def quota(self):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
264
        d = defaultdict(int)
265
        for q in self.astakosgroupquota_set.select_related().all():
266
            d[q.resource] += q.uplimit or inf
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
267
        return d
268

Olga Brani's avatar
Olga Brani committed
269
270
271
272
273
274
275
276
277
278
279
280
    def add_policy(self, service, resource, uplimit, update=True):
        """Raises ObjectDoesNotExist, IntegrityError"""
        resource = Resource.objects.get(service__name=service, name=resource)
        if update:
            AstakosGroupQuota.objects.update_or_create(
                group=self,
                resource=resource,
                defaults={'uplimit': uplimit}
            )
        else:
            q = self.astakosgroupquota_set
            q.create(resource=resource, uplimit=uplimit)
281

Olga Brani's avatar
Olga Brani committed
282
283
284
285
286
287
288
289
290
291
292
293
    @property
    def policies(self):
        return self.astakosgroupquota_set.select_related().all()

    @policies.setter
    def policies(self, policies):
        for p in policies:
            service = p.get('service', None)
            resource = p.get('resource', None)
            uplimit = p.get('uplimit', 0)
            update = p.get('update', True)
            self.add_policy(service, resource, uplimit, update)
294

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
295
296
297
    @property
    def owners(self):
        return self.owner.all()
298

299
300
301
302
    @property
    def owner_details(self):
        return self.owner.select_related().all()

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
303
304
305
306
    @owners.setter
    def owners(self, l):
        self.owner = l
        map(self.approve_member, l)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
307

308

309

310
class AstakosUserManager(UserManager):
311
312
313
314
315
316
317
318
319
320

    def get_auth_provider_user(self, provider, **kwargs):
        """
        Retrieve AstakosUser instance associated with the specified third party
        id.
        """
        kwargs = dict(map(lambda x: ('auth_providers__%s' % x[0], x[1]),
                          kwargs.iteritems()))
        return self.get(auth_providers__module=provider, **kwargs)

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
321
class AstakosUser(User):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
322
323
324
    """
    Extends ``django.contrib.auth.models.User`` by defining additional fields.
    """
325
326
327
328
329
330
331
332
333
334
335
336
    affiliation = models.CharField('Affiliation', max_length=255, blank=True,
                                   null=True)

    # DEPRECATED FIELDS: provider, third_party_identifier moved in
    #                    AstakosUserProvider model.
    provider = models.CharField('Provider', max_length=255, blank=True,
                                null=True)
    # ex. screen_name for twitter, eppn for shibboleth
    third_party_identifier = models.CharField('Third-party identifier',
                                              max_length=255, null=True,
                                              blank=True)

Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
337

338
    #for invitations
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
339
    user_level = DEFAULT_USER_LEVEL
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
340
    level = models.IntegerField('Inviter level', default=user_level)
341
342
    invitations = models.IntegerField(
        'Invitations left', default=INVITATIONS_PER_LEVEL.get(user_level, 0))
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
343

344
    auth_token = models.CharField('Authentication Token', max_length=32,
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
345
346
                                  null=True, blank=True)
    auth_token_created = models.DateTimeField('Token creation date', null=True)
347
348
    auth_token_expires = models.DateTimeField(
        'Token expiration date', null=True)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
349

350
    updated = models.DateTimeField('Update date')
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
351
    is_verified = models.BooleanField('Is verified?', default=False)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
352

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
353
    email_verified = models.BooleanField('Email verified?', default=False)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
354

355
    has_credits = models.BooleanField('Has credits?', default=False)
356
    has_signed_terms = models.BooleanField(
Olga Brani's avatar
Olga Brani committed
357
        'I agree with the terms', default=False)
358
359
360
361
362
363
364
365
366
367
368
    date_signed_terms = models.DateTimeField(
        'Signed terms date', null=True, blank=True)

    activation_sent = models.DateTimeField(
        'Activation sent data', null=True, blank=True)

    policy = models.ManyToManyField(
        Resource, null=True, through='AstakosUserQuota')

    astakos_groups = models.ManyToManyField(
        AstakosGroup, verbose_name=_('agroups'), blank=True,
Olga Brani's avatar
Olga Brani committed
369
        help_text=_(astakos_messages.ASTAKOSUSER_GROUPS_HELP),
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
370
        through='Membership')
371

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
372
    __has_signed_terms = False
Olga Brani's avatar
Olga Brani committed
373
374
    disturbed_quota = models.BooleanField('Needs quotaholder syncing',
                                           default=False, db_index=True)
375
376

    objects = AstakosUserManager()
377

378
379
380
    owner = models.ManyToManyField(
        AstakosGroup, related_name='owner', null=True)

381
382
    class Meta:
        unique_together = ("provider", "third_party_identifier")
383

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
384
385
386
    def __init__(self, *args, **kwargs):
        super(AstakosUser, self).__init__(*args, **kwargs)
        self.__has_signed_terms = self.has_signed_terms
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
387
        if not self.id:
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
388
            self.is_active = False
389

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
390
391
    @property
    def realname(self):
392
        return '%s %s' % (self.first_name, self.last_name)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
393

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
394
395
396
397
398
399
400
401
    @realname.setter
    def realname(self, value):
        parts = value.split(' ')
        if len(parts) == 2:
            self.first_name = parts[0]
            self.last_name = parts[1]
        else:
            self.last_name = parts[0]
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
402

Olga Brani's avatar
Olga Brani committed
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
    def add_permission(self, pname):
        if self.has_perm(pname):
            return
        p, created = Permission.objects.get_or_create(codename=pname,
                                                      name=pname.capitalize(),
                                                      content_type=content_type)
        self.user_permissions.add(p)

    def remove_permission(self, pname):
        if self.has_perm(pname):
            return
        p = Permission.objects.get(codename=pname,
                                   content_type=content_type)
        self.user_permissions.remove(p)

418
419
420
    @property
    def invitation(self):
        try:
421
            return Invitation.objects.get(username=self.email)
422
423
        except Invitation.DoesNotExist:
            return None
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
424

Olga Brani's avatar
Olga Brani committed
425
426
427
428
429
430
431
    def invite(self, email, realname):
        inv = Invitation(inviter=self, username=email, realname=realname)
        inv.save()
        send_invitation(inv)
        self.invitations = max(0, self.invitations - 1)
        self.save()

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
432
433
    @property
    def quota(self):
Olga Brani's avatar
Olga Brani committed
434
        """Returns a dict with the sum of quota limits per resource"""
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
435
        d = defaultdict(int)
Olga Brani's avatar
Olga Brani committed
436
        for q in self.policies:
437
            d[q.resource] += q.uplimit or inf
Olga Brani's avatar
Olga Brani committed
438
        for m in self.extended_groups:
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
439
440
441
            if not m.is_approved:
                continue
            g = m.group
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
442
443
            if not g.is_enabled:
                continue
444
            for r, uplimit in g.quota.iteritems():
445
                d[r] += uplimit or inf
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
446
447
        # TODO set default for remaining
        return d
448

Olga Brani's avatar
Olga Brani committed
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
    @property
    def policies(self):
        return self.astakosuserquota_set.select_related().all()

    @policies.setter
    def policies(self, policies):
        for p in policies:
            service = policies.get('service', None)
            resource = policies.get('resource', None)
            uplimit = policies.get('uplimit', 0)
            update = policies.get('update', True)
            self.add_policy(service, resource, uplimit, update)

    def add_policy(self, service, resource, uplimit, update=True):
        """Raises ObjectDoesNotExist, IntegrityError"""
        resource = Resource.objects.get(service__name=service, name=resource)
        if update:
            AstakosUserQuota.objects.update_or_create(user=self,
                                                      resource=resource,
                                                      defaults={'uplimit': uplimit})
        else:
            q = self.astakosuserquota_set
            q.create(resource=resource, uplimit=uplimit)

    def remove_policy(self, service, resource):
        """Raises ObjectDoesNotExist, IntegrityError"""
        resource = Resource.objects.get(service__name=service, name=resource)
        q = self.policies.get(resource=resource).delete()

    @property
    def extended_groups(self):
        return self.membership_set.select_related().all()

    @extended_groups.setter
    def extended_groups(self, groups):
        #TODO exceptions
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
485
        for name in (groups or ()):
Olga Brani's avatar
Olga Brani committed
486
487
488
            group = AstakosGroup.objects.get(name=name)
            self.membership_set.create(group=group)

489
490
491
    def save(self, update_timestamps=True, **kwargs):
        if update_timestamps:
            if not self.id:
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
492
                self.date_joined = datetime.now()
493
            self.updated = datetime.now()
494

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
495
496
497
        # update date_signed_terms if necessary
        if self.__has_signed_terms != self.has_signed_terms:
            self.date_signed_terms = datetime.now()
498

499
500
        if not self.id:
            # set username
501
            self.username = self.email
502

503
        self.validate_unique_email_isactive()
504
505
506
        if self.is_active and self.activation_sent:
            # reset the activation sent
            self.activation_sent = None
507

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
508
        super(AstakosUser, self).save(**kwargs)
509

510
    def renew_token(self, flush_sessions=False, current_key=None):
511
        md5 = hashlib.md5()
512
        md5.update(settings.SECRET_KEY)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
513
        md5.update(self.username)
514
515
        md5.update(self.realname.encode('ascii', 'ignore'))
        md5.update(asctime())
516

517
518
519
        self.auth_token = b64encode(md5.digest())
        self.auth_token_created = datetime.now()
        self.auth_token_expires = self.auth_token_created + \
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
520
                                  timedelta(hours=AUTH_TOKEN_DURATION)
521
522
        if flush_sessions:
            self.flush_sessions(current_key)
523
        msg = 'Token renewed for %s' % self.email
524
        logger.log(LOGGING_LEVEL, msg)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
525

526
527
528
529
    def flush_sessions(self, current_key=None):
        q = self.sessions
        if current_key:
            q = q.exclude(session_key=current_key)
530

531
532
533
        keys = q.values_list('session_key', flat=True)
        if keys:
            msg = 'Flushing sessions: %s' % ','.join(keys)
534
            logger.log(LOGGING_LEVEL, msg, [])
535
536
537
538
539
        engine = import_module(settings.SESSION_ENGINE)
        for k in keys:
            s = engine.SessionStore(k)
            s.flush()

540
    def __unicode__(self):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
541
        return '%s (%s)' % (self.realname, self.email)
542

543
    def conflicting_email(self):
544
        q = AstakosUser.objects.exclude(username=self.username)
545
        q = q.filter(email__iexact=self.email)
546
547
548
        if q.count() != 0:
            return True
        return False
549

550
    def validate_unique_email_isactive(self):
551
552
553
        """
        Implements a unique_together constraint for email and is_active fields.
        """
554
        q = AstakosUser.objects.all()
555
556
        q = q.filter(email = self.email)
        q = q.filter(is_active = self.is_active)
557
558
        if self.id:
            q = q.filter(~Q(id = self.id))
559
        if q.count() != 0:
Olga Brani's avatar
Olga Brani committed
560
            raise ValidationError({'__all__': [_(astakos_messages.UNIQUE_EMAIL_IS_ACTIVE_CONSTRAIN_ERR)]})
561

562
    @property
563
564
565
566
567
568
569
570
571
572
    def signed_terms(self):
        term = get_latest_terms()
        if not term:
            return True
        if not self.has_signed_terms:
            return False
        if not self.date_signed_terms:
            return False
        if self.date_signed_terms < term.date:
            self.has_signed_terms = False
573
            self.date_signed_terms = None
574
575
576
577
            self.save()
            return False
        return True

578
579
580
581
582
583
584
585
586
587
588
589
590
591
    def set_invitations_level(self):
        """
        Update user invitation level
        """
        level = self.invitation.inviter.level + 1
        self.level = level
        self.invitations = INVITATIONS_PER_LEVEL.get(level, 0)

    def can_login_with_auth_provider(self, provider):
        if not self.has_auth_provider(provider):
            return False
        else:
            return auth_providers.get_provider(provider).is_available_for_login()

592
    def can_add_auth_provider(self, provider, **kwargs):
593
594
595
        provider_settings = auth_providers.get_provider(provider)
        if not provider_settings.is_available_for_login():
            return False
596

597
598
599
        if self.has_auth_provider(provider) and \
           provider_settings.one_per_user:
            return False
600
601
602
603
604
605
606
607
608
609
610

        if 'identifier' in kwargs:
            try:
                # provider with specified params already exist
                existing_user = AstakosUser.objects.get_auth_provider_user(provider,
                                                                   **kwargs)
            except AstakosUser.DoesNotExist:
                return True
            else:
                return False

611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
        return True

    def can_remove_auth_provider(self, provider):
        if len(self.get_active_auth_providers()) <= 1:
            return False
        return True

    def can_change_password(self):
        return self.has_auth_provider('local', auth_backend='astakos')

    def has_auth_provider(self, provider, **kwargs):
        return bool(self.auth_providers.filter(module=provider,
                                               **kwargs).count())

    def add_auth_provider(self, provider, **kwargs):
626
627
628
629
        if self.can_add_auth_provider(provider, **kwargs):
            self.auth_providers.create(module=provider, active=True, **kwargs)
        else:
            raise Exception('Cannot add provider')
630
631
632
633
634
635
636
637
638
639
640
641

    def add_pending_auth_provider(self, pending):
        """
        Convert PendingThirdPartyUser object to AstakosUserAuthProvider entry for
        the current user.
        """
        if not isinstance(pending, PendingThirdPartyUser):
            pending = PendingThirdPartyUser.objects.get(token=pending)

        provider = self.add_auth_provider(pending.provider,
                               identifier=pending.third_party_identifier)

642
        if email_re.match(pending.email or '') and pending.email != self.email:
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
            self.additionalmail_set.get_or_create(email=pending.email)

        pending.delete()
        return provider

    def remove_auth_provider(self, provider, **kwargs):
        self.auth_providers.get(module=provider, **kwargs).delete()

    # user urls
    def get_resend_activation_url(self):
        return reverse('send_activation', {'user_id': self.pk})

    def get_activation_url(self, nxt=False):
        url = "%s?auth=%s" % (reverse('astakos.im.views.activate'),
                                 quote(self.auth_token))
        if nxt:
            url += "&next=%s" % quote(nxt)
        return url

    def get_password_reset_url(self, token_generator=default_token_generator):
        return reverse('django.contrib.auth.views.password_reset_confirm',
                          kwargs={'uidb36':int_to_base36(self.id),
                                  'token':token_generator.make_token(self)})

    def get_auth_providers(self):
        return self.auth_providers.all()

    def get_available_auth_providers(self):
        """
        Returns a list of providers available for user to connect to.
        """
        providers = []
        for module, provider_settings in auth_providers.PROVIDERS.iteritems():
676
            if self.can_add_auth_provider(module):
677
678
679
680
681
682
683
684
685
686
687
                providers.append(provider_settings(self))

        return providers

    def get_active_auth_providers(self):
        providers = []
        for provider in self.auth_providers.active():
            if auth_providers.get_provider(provider.module).is_available_for_login():
                providers.append(provider)
        return providers

688
689
690
691
    @property
    def auth_providers_display(self):
        return ",".join(map(lambda x:unicode(x), self.auth_providers.active()))

692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732

class AstakosUserAuthProviderManager(models.Manager):

    def active(self):
        return self.filter(active=True)


class AstakosUserAuthProvider(models.Model):
    """
    Available user authentication methods.
    """
    affiliation = models.CharField('Affiliation', max_length=255, blank=True,
                                   null=True, default=None)
    user = models.ForeignKey(AstakosUser, related_name='auth_providers')
    module = models.CharField('Provider', max_length=255, blank=False,
                                default='local')
    identifier = models.CharField('Third-party identifier',
                                              max_length=255, null=True,
                                              blank=True)
    active = models.BooleanField(default=True)
    auth_backend = models.CharField('Backend', max_length=255, blank=False,
                                   default='astakos')

    objects = AstakosUserAuthProviderManager()

    class Meta:
        unique_together = (('identifier', 'module', 'user'), )

    @property
    def settings(self):
        return auth_providers.get_provider(self.module)

    @property
    def details_display(self):
        return self.settings.details_tpl % self.__dict__

    def can_remove(self):
        return self.user.can_remove_auth_provider(self.module)

    def delete(self, *args, **kwargs):
        ret = super(AstakosUserAuthProvider, self).delete(*args, **kwargs)
733
734
735
        if self.module == 'local':
            self.user.set_unusable_password()
            self.user.save()
736
737
        return ret

738
739
740
    def __repr__(self):
        return '<AstakosUserAuthProvider %s:%s>' % (self.module, self.identifier)

741
742
743
744
745
746
747
748
    def __unicode__(self):
        if self.identifier:
            return "%s:%s" % (self.module, self.identifier)
        if self.auth_backend:
            return "%s:%s" % (self.module, self.auth_backend)
        return self.module


749

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
750
751
752
class Membership(models.Model):
    person = models.ForeignKey(AstakosUser)
    group = models.ForeignKey(AstakosGroup)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
753
754
    date_requested = models.DateField(default=datetime.now(), blank=True)
    date_joined = models.DateField(null=True, db_index=True, blank=True)
755

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
756
757
    class Meta:
        unique_together = ("person", "group")
758

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
759
    def save(self, *args, **kwargs):
760
761
762
        if not self.id:
            if not self.group.moderation_enabled:
                self.date_joined = datetime.now()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
763
        super(Membership, self).save(*args, **kwargs)
764

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
765
766
767
768
769
    @property
    def is_approved(self):
        if self.date_joined:
            return True
        return False
770

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
771
    def approve(self):
772
773
        if self.is_approved:
            return
Olga Brani's avatar
Olga Brani committed
774
        if self.group.max_participants:
775
            assert len(self.group.approved_members) + 1 <= self.group.max_participants, \
776
            'Maximum participant number has been reached.'
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
777
778
        self.date_joined = datetime.now()
        self.save()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
779
        quota_disturbed.send(sender=self, users=(self.person,))
780

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
781
782
    def disapprove(self):
        self.delete()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
783
        quota_disturbed.send(sender=self, users=(self.person,))
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
784

Olga Brani's avatar
Olga Brani committed
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
class AstakosQuotaManager(models.Manager):
    def _update_or_create(self, **kwargs):
        assert kwargs, \
            'update_or_create() must be passed at least one keyword argument'
        obj, created = self.get_or_create(**kwargs)
        defaults = kwargs.pop('defaults', {})
        if created:
            return obj, True, False
        else:
            try:
                params = dict(
                    [(k, v) for k, v in kwargs.items() if '__' not in k])
                params.update(defaults)
                for attr, val in params.items():
                    if hasattr(obj, attr):
                        setattr(obj, attr, val)
                sid = transaction.savepoint()
                obj.save(force_update=True)
                transaction.savepoint_commit(sid)
                return obj, False, True
            except IntegrityError, e:
                transaction.savepoint_rollback(sid)
                try:
                    return self.get(**kwargs), False, False
                except self.model.DoesNotExist:
                    raise e

    update_or_create = _update_or_create
813

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
814
class AstakosGroupQuota(models.Model):
Olga Brani's avatar
Olga Brani committed
815
    objects = AstakosQuotaManager()
816
    limit = models.PositiveIntegerField('Limit', null=True)    # obsolete field
817
    uplimit = models.BigIntegerField('Up limit', null=True)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
818
819
    resource = models.ForeignKey(Resource)
    group = models.ForeignKey(AstakosGroup, blank=True)
820

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
821
822
823
824
    class Meta:
        unique_together = ("resource", "group")

class AstakosUserQuota(models.Model):
Olga Brani's avatar
Olga Brani committed
825
    objects = AstakosQuotaManager()
826
    limit = models.PositiveIntegerField('Limit', null=True)    # obsolete field
827
    uplimit = models.BigIntegerField('Up limit', null=True)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
828
829
    resource = models.ForeignKey(Resource)
    user = models.ForeignKey(AstakosUser)
830

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
831
832
    class Meta:
        unique_together = ("resource", "user")
833

834

835
836
837
838
class ApprovalTerms(models.Model):
    """
    Model for approval terms
    """
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
839

840
841
    date = models.DateTimeField(
        'Issue date', db_index=True, default=datetime.now())
842
843
    location = models.CharField('Terms location', max_length=255)

844

845
class Invitation(models.Model):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
846
847
848
    """
    Model for registring invitations
    """
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
849
    inviter = models.ForeignKey(AstakosUser, related_name='invitations_sent',
850
851
                                null=True)
    realname = models.CharField('Real name', max_length=255)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
852
    username = models.CharField('Unique ID', max_length=255, unique=True)
853
854
855
856
    code = models.BigIntegerField('Invitation code', db_index=True)
    is_consumed = models.BooleanField('Consumed?', default=False)
    created = models.DateTimeField('Creation date', auto_now_add=True)
    consumed = models.DateTimeField('Consumption date', null=True, blank=True)
857

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
858
859
    def __init__(self, *args, **kwargs):
        super(Invitation, self).__init__(*args, **kwargs)
860
861
        if not self.id:
            self.code = _generate_invitation_code()
862

863
864
865
866
    def consume(self):
        self.is_consumed = True
        self.consumed = datetime.now()
        self.save()
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
867

868
    def __unicode__(self):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
869
        return '%s -> %s [%d]' % (self.inviter, self.username, self.code)
870

871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891

class EmailChangeManager(models.Manager):
    @transaction.commit_on_success
    def change_email(self, activation_key):
        """
        Validate an activation key and change the corresponding
        ``User`` if valid.

        If the key is valid and has not expired, return the ``User``
        after activating.

        If the key is not valid or has expired, return ``None``.

        If the key is valid but the ``User`` is already active,
        return ``None``.

        After successful email change the activation record is deleted.

        Throws ValueError if there is already
        """
        try:
892
893
            email_change = self.model.objects.get(
                activation_key=activation_key)
894
895
896
897
898
            if email_change.activation_key_expired():
                email_change.delete()
                raise EmailChange.DoesNotExist
            # is there an active user with this address?
            try:
899
                AstakosUser.objects.get(email__iexact=email_change.new_email_address)
900
901
902
            except AstakosUser.DoesNotExist:
                pass
            else:
Olga Brani's avatar
Olga Brani committed
903
                raise ValueError(_(astakos_messages.NEW_EMAIL_ADDR_RESERVED))
904
905
906
907
908
909
910
            # update user
            user = AstakosUser.objects.get(pk=email_change.user_id)
            user.email = email_change.new_email_address
            user.save()
            email_change.delete()
            return user
        except EmailChange.DoesNotExist:
Olga Brani's avatar
Olga Brani committed
911
            raise ValueError(_(astakos_messages.INVALID_ACTIVATION_KEY))
912
913
914


class EmailChange(models.Model):
Olga Brani's avatar
Olga Brani committed
915
    new_email_address = models.EmailField(_(u'new e-mail address'),
Olga Brani's avatar
Olga Brani committed
916
                                          help_text=_(astakos_messages.EMAIL_CHANGE_NEW_ADDR_HELP))
917
918
    user = models.ForeignKey(
        AstakosUser, unique=True, related_name='emailchange_user')
919
    requested_at = models.DateTimeField(default=datetime.now())
920
921
    activation_key = models.CharField(
        max_length=40, unique=True, db_index=True)
922
923
924
925
926

    objects = EmailChangeManager()

    def activation_key_expired(self):
        expiration_date = timedelta(days=EMAILCHANGE_ACTIVATION_DAYS)
927
928
        return self.requested_at + expiration_date < datetime.now()

929

930
931
932
933
934
class AdditionalMail(models.Model):
    """
    Model for registring invitations
    """
    owner = models.ForeignKey(AstakosUser)
935
    email = models.EmailField()
936

937

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
938
939
def _generate_invitation_code():
    while True:
940
        code = randint(1, 2L ** 63 - 1)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
941
942
943
944
945
946
        try:
            Invitation.objects.get(code=code)
            # An invitation with this code already exists, try again
        except Invitation.DoesNotExist:
            return code

947

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
948
949
950
951
952
953
954
955
def get_latest_terms():
    try:
        term = ApprovalTerms.objects.order_by('-id')[0]
        return term
    except IndexError:
        pass
    return None

956
957
958
959
960
961
class PendingThirdPartyUser(models.Model):
    """
    Model for registring successful third party user authentications
    """
    third_party_identifier = models.CharField('Third-party identifier', max_length=255, null=True, blank=True)
    provider = models.CharField('Provider', max_length=255, blank=True)
962
    email = models.EmailField(_('e-mail address'), blank=True, null=True)
963
964
965
966
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    affiliation = models.CharField('Affiliation', max_length=255, blank=True)
    username = models.CharField(_('username'), max_length=30, unique=True, help_text=_("Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters"))
967
968
969
    token = models.CharField('Token', max_length=255, null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True, null=True, blank=True)

970
971
    class Meta:
        unique_together = ("provider", "third_party_identifier")
972
973
974
975
976
977
978
979
980
981
982
983
984

    @property
    def realname(self):
        return '%s %s' %(self.first_name, self.last_name)

    @realname.setter
    def realname(self, value):
        parts = value.split(' ')
        if len(parts) == 2:
            self.first_name = parts[0]
            self.last_name = parts[1]
        else:
            self.last_name = parts[0]
985

986
987
988
989
990
991
992
993
994
995
996
    def save(self, **kwargs):
        if not self.id:
            # set username
            while not self.username:
                username =  uuid.uuid4().hex[:30]
                try:
                    AstakosUser.objects.get(username = username)
                except AstakosUser.DoesNotExist, e:
                    self.username = username
        super(PendingThirdPartyUser, self).save(**kwargs)

997
998
999
1000
1001
    def generate_token(self):
        self.password = self.third_party_identifier
        self.last_login = datetime.now()
        self.token = default_token_generator.make_token(self)

1002
1003
1004
1005
class SessionCatalog(models.Model):
    session_key = models.CharField(_('session key'), max_length=40)
    user = models.ForeignKey(AstakosUser, related_name='sessions', null=True)

1006

1007
1008
1009
1010
1011
1012
1013
def create_astakos_user(u):
    try:
        AstakosUser.objects.get(user_ptr=u.pk)
    except AstakosUser.DoesNotExist:
        extended_user = AstakosUser(user_ptr_id=u.pk)
        extended_user.__dict__.update(u.__dict__)
        extended_user.save()
Olga Brani's avatar
Olga Brani committed
1014
1015
        if not extended_user.has_auth_provider('local'):
            extended_user.add_auth_provider('local')
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1016
1017
    except BaseException, e:
        logger.exception(e)
1018

1019

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1020
1021
def fix_superusers(sender, **kwargs):
    # Associate superusers with AstakosUser
1022
1023
1024
1025
1026
    admins = User.objects.filter(is_superuser=True)
    for u in admins:
        create_astakos_user(u)


Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1027
def user_post_save(sender, instance, created, **kwargs):
1028
1029
    if not created:
        return
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1030
1031
    create_astakos_user(instance)

1032

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1033
def set_default_group(user):
1034
    try:
1035
1036
1037
        default = AstakosGroup.objects.get(name='default')
        Membership(
            group=default, person=user, date_joined=datetime.now()).save()
1038
1039
    except AstakosGroup.DoesNotExist, e:
        logger.exception(e)
1040

1041

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1042
1043
1044
1045
def astakosuser_pre_save(sender, instance, **kwargs):
    instance.aquarium_report = False
    instance.new = False
    try:
1046
        db_instance = AstakosUser.objects.get(id=instance.id)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1047
1048
1049
1050
1051
1052
1053
    except AstakosUser.DoesNotExist:
        # create event
        instance.aquarium_report = True
        instance.new = True
    else:
        get = AstakosUser.__getattribute__
        l = filter(lambda f: get(db_instance, f) != get(instance, f),
Olga Brani's avatar
Olga Brani committed
1054
                   BILLING_FIELDS)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1055
1056
        instance.aquarium_report = True if l else False

1057

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1058
1059
1060
1061
1062
1063
1064
1065
1066
def astakosuser_post_save(sender, instance, created, **kwargs):
    if instance.aquarium_report:
        report_user_event(instance, create=instance.new)
    if not created:
        return
    set_default_group(instance)
    # TODO handle socket.error & IOError
    register_users((instance,))

1067

1068
1069
1070
1071
1072
1073
def resource_post_save(sender, instance, created, **kwargs):
    if not created:
        return
    register_resources((instance,))


Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
def send_quota_disturbed(sender, instance, **kwargs):
    users = []
    extend = users.extend
    if sender == Membership:
        if not instance.group.is_enabled:
            return
        extend([instance.person])
    elif sender == AstakosUserQuota:
        extend([instance.user])
    elif sender == AstakosGroupQuota:
        if not instance.group.is_enabled:
            return
        extend(instance.group.astakosuser_set.all())
    elif sender == AstakosGroup:
        if not instance.is_enabled:
            return
    quota_disturbed.send(sender=sender, users=users)

1092

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1093
def on_quota_disturbed(sender, users, **kwargs):
1094
#     print '>>>', locals()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1095
1096
1097
    if not users:
        return
    send_quota(users)
1098
1099

def renew_token(sender, instance, **kwargs):
1100
    if not instance.auth_token:
1101
1102
        instance.renew_token()

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1103
1104
1105
1106
post_syncdb.connect(fix_superusers)
post_save.connect(user_post_save, sender=User)
pre_save.connect(astakosuser_pre_save, sender=AstakosUser)
post_save.connect(astakosuser_post_save, sender=AstakosUser)
1107
post_save.connect(resource_post_save, sender=Resource)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1108
1109
1110
1111
1112
1113
1114
1115
1116

quota_disturbed = Signal(providing_args=["users"])
quota_disturbed.connect(on_quota_disturbed)

post_delete.connect(send_quota_disturbed, sender=AstakosGroup)
post_delete.connect(send_quota_disturbed, sender=Membership)
post_save.connect(send_quota_disturbed, sender=AstakosUserQuota)
post_delete.connect(send_quota_disturbed, sender=AstakosUserQuota)
post_save.connect(send_quota_disturbed, sender=AstakosGroupQuota)
1117
post_delete.connect(send_quota_disturbed, sender=AstakosGroupQuota)
1118

1119
pre_save.connect(renew_token, sender=AstakosUser)
1120
pre_save.connect(renew_token, sender=Service)