1 # Copyright 2011-2012 GRNET S.A. All rights reserved.
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
7 # 1. Redistributions of source code must retain the above
8 # copyright notice, this list of conditions and the following
11 # 2. Redistributions in binary form must reproduce the above
12 # copyright notice, this list of conditions and the following
13 # disclaimer in the documentation and/or other materials
14 # provided with the distribution.
16 # THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17 # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23 # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24 # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 # POSSIBILITY OF SUCH DAMAGE.
29 # The views and conclusions contained in the software and
30 # documentation are those of the authors and should not be
31 # interpreted as representing official policies, either expressed
32 # or implied, of GRNET S.A.
39 from time import asctime
40 from datetime import datetime, timedelta
41 from base64 import b64encode
42 from urlparse import urlparse, urlunparse
43 from random import randint
44 from collections import defaultdict
45 from south.signals import post_migrate
47 from django.db import models, IntegrityError
48 from django.contrib.auth.models import User, UserManager, Group
49 from django.utils.translation import ugettext as _
50 from django.core.exceptions import ValidationError
51 from django.template.loader import render_to_string
52 from django.core.mail import send_mail
53 from django.db import transaction
54 from django.db.models.signals import post_save, post_syncdb
55 from django.db.models import Q, Count
57 from astakos.im.settings import DEFAULT_USER_LEVEL, INVITATIONS_PER_LEVEL, \
58 AUTH_TOKEN_DURATION, BILLING_FIELDS, QUEUE_CONNECTION, SITENAME, \
59 EMAILCHANGE_ACTIVATION_DAYS, LOGGING_LEVEL
61 QUEUE_CLIENT_ID = 3 # Astakos.
63 logger = logging.getLogger(__name__)
65 class Service(models.Model):
66 name = models.CharField('Name', max_length=255, unique=True, db_index=True)
67 url = models.FilePathField()
68 icon = models.FilePathField(blank=True)
69 auth_token = models.CharField('Authentication Token', max_length=32,
70 null=True, blank=True)
71 auth_token_created = models.DateTimeField('Token creation date', null=True)
72 auth_token_expires = models.DateTimeField('Token expiration date', null=True)
74 def save(self, **kwargs):
78 super(Service, self).save(**kwargs)
80 def renew_token(self):
82 md5.update(self.name.encode('ascii', 'ignore'))
83 md5.update(self.url.encode('ascii', 'ignore'))
86 self.auth_token = b64encode(md5.digest())
87 self.auth_token_created = datetime.now()
88 self.auth_token_expires = self.auth_token_created + \
89 timedelta(hours=AUTH_TOKEN_DURATION)
94 class ResourceMetadata(models.Model):
95 key = models.CharField('Name', max_length=255, unique=True, db_index=True)
96 value = models.CharField('Value', max_length=255)
98 class Resource(models.Model):
99 name = models.CharField('Name', max_length=255, unique=True, db_index=True)
100 meta = models.ManyToManyField(ResourceMetadata)
101 service = models.ForeignKey(Service)
104 return '%s : %s' % (self.service, self.name)
106 class GroupKind(models.Model):
107 name = models.CharField('Name', max_length=255, unique=True, db_index=True)
112 class AstakosGroup(Group):
113 kind = models.ForeignKey(GroupKind)
114 desc = models.TextField('Description', null=True)
115 policy = models.ManyToManyField(Resource, null=True, blank=True, through='AstakosGroupQuota')
116 creation_date = models.DateTimeField('Creation date', default=datetime.now())
117 issue_date = models.DateTimeField('Issue date', null=True)
118 expiration_date = models.DateTimeField('Expiration date', null=True)
119 moderation_enabled = models.BooleanField('Moderated membership?', default=True)
120 approval_date = models.DateTimeField('Activation date', null=True, blank=True)
121 estimated_participants = models.PositiveIntegerField('Estimated #participants', null=True)
124 def is_disabled(self):
125 if not self.approval_date:
130 def is_enabled(self):
133 if not self.issue_date:
135 if not self.expiration_date:
138 if self.issue_date > now:
140 if now >= self.expiration_date:
145 def participants(self):
146 return len(self.approved_members)
149 self.approval_date = datetime.now()
153 self.approval_date = None
156 def approve_member(self, person):
158 self.membership_set.create(person=person, date_joined=datetime.now())
159 except IntegrityError:
160 m = self.membership_set.get(person=person)
161 m.date_joined = datetime.now()
164 def disapprove_member(self, person):
165 self.membership_set.remove(person=person)
169 return map(lambda m:m.person, self.membership_set.all())
172 def approved_members(self):
173 f = filter(lambda m:m.is_approved, self.membership_set.all())
174 return map(lambda m:m.person, f)
179 for q in self.astakosgroupquota_set.all():
180 d[q.resource.name] = q.limit
184 def has_undefined_policies(self):
185 # TODO: can avoid query?
186 return Resource.objects.filter(~Q(astakosgroup=self)).exists()
188 class AstakosUser(User):
190 Extends ``django.contrib.auth.models.User`` by defining additional fields.
192 # Use UserManager to get the create_user method, etc.
193 objects = UserManager()
195 affiliation = models.CharField('Affiliation', max_length=255, blank=True)
196 provider = models.CharField('Provider', max_length=255, blank=True)
199 user_level = DEFAULT_USER_LEVEL
200 level = models.IntegerField('Inviter level', default=user_level)
201 invitations = models.IntegerField('Invitations left', default=INVITATIONS_PER_LEVEL.get(user_level, 0))
203 auth_token = models.CharField('Authentication Token', max_length=32,
204 null=True, blank=True)
205 auth_token_created = models.DateTimeField('Token creation date', null=True)
206 auth_token_expires = models.DateTimeField('Token expiration date', null=True)
208 updated = models.DateTimeField('Update date')
209 is_verified = models.BooleanField('Is verified?', default=False)
211 # ex. screen_name for twitter, eppn for shibboleth
212 third_party_identifier = models.CharField('Third-party identifier', max_length=255, null=True, blank=True)
214 email_verified = models.BooleanField('Email verified?', default=False)
216 has_credits = models.BooleanField('Has credits?', default=False)
217 has_signed_terms = models.BooleanField('Agree with the terms?', default=False)
218 date_signed_terms = models.DateTimeField('Signed terms date', null=True, blank=True)
220 activation_sent = models.DateTimeField('Activation sent data', null=True, blank=True)
222 policy = models.ManyToManyField(Resource, null=True, through='AstakosUserQuota')
224 astakos_groups = models.ManyToManyField(AstakosGroup, verbose_name=_('agroups'), blank=True,
225 help_text=_("In addition to the permissions manually assigned, this user will also get all permissions granted to each group he/she is in."),
226 through='Membership')
228 __has_signed_terms = False
231 owner = models.ManyToManyField(AstakosGroup, related_name='owner', null=True)
234 unique_together = ("provider", "third_party_identifier")
236 def __init__(self, *args, **kwargs):
237 super(AstakosUser, self).__init__(*args, **kwargs)
238 self.__has_signed_terms = self.has_signed_terms
240 self.__groupnames = [g.name for g in self.astakos_groups.all()]
242 self.is_active = False
246 return '%s %s' %(self.first_name, self.last_name)
249 def realname(self, value):
250 parts = value.split(' ')
252 self.first_name = parts[0]
253 self.last_name = parts[1]
255 self.last_name = parts[0]
258 def invitation(self):
260 return Invitation.objects.get(username=self.email)
261 except Invitation.DoesNotExist:
267 for q in self.astakosuserquota_set.all():
268 d[q.resource.name] += q.limit
269 for g in self.astakos_groups.all():
272 for r, limit in g.quota.iteritems():
274 # TODO set default for remaining
277 def save(self, update_timestamps=True, **kwargs):
278 if update_timestamps:
280 self.date_joined = datetime.now()
281 self.updated = datetime.now()
283 # update date_signed_terms if necessary
284 if self.__has_signed_terms != self.has_signed_terms:
285 self.date_signed_terms = datetime.now()
289 while not self.username:
290 username = uuid.uuid4().hex[:30]
292 AstakosUser.objects.get(username = username)
293 except AstakosUser.DoesNotExist, e:
294 self.username = username
295 if not self.provider:
296 self.provider = 'local'
297 report_user_event(self)
298 self.validate_unique_email_isactive()
299 if self.is_active and self.activation_sent:
300 # reset the activation sent
301 self.activation_sent = None
303 super(AstakosUser, self).save(**kwargs)
305 # set group if does not exist
306 groupname = 'shibboleth' if self.provider == 'shibboleth' else 'default'
307 if groupname not in self.__groupnames:
309 group = AstakosGroup.objects.get(name = groupname)
310 Membership(group=group, person=self, date_joined=datetime.now()).save()
311 except AstakosGroup.DoesNotExist, e:
314 def renew_token(self):
316 md5.update(self.username)
317 md5.update(self.realname.encode('ascii', 'ignore'))
318 md5.update(asctime())
320 self.auth_token = b64encode(md5.digest())
321 self.auth_token_created = datetime.now()
322 self.auth_token_expires = self.auth_token_created + \
323 timedelta(hours=AUTH_TOKEN_DURATION)
324 msg = 'Token renewed for %s' % self.email
325 logger._log(LOGGING_LEVEL, msg, [])
327 def __unicode__(self):
330 def conflicting_email(self):
331 q = AstakosUser.objects.exclude(username = self.username)
332 q = q.filter(email = self.email)
337 def validate_unique_email_isactive(self):
339 Implements a unique_together constraint for email and is_active fields.
341 q = AstakosUser.objects.exclude(username = self.username)
342 q = q.filter(email = self.email)
343 q = q.filter(is_active = self.is_active)
345 raise ValidationError({'__all__':[_('Another account with the same email & is_active combination found.')]})
347 def signed_terms(self):
348 term = get_latest_terms()
351 if not self.has_signed_terms:
353 if not self.date_signed_terms:
355 if self.date_signed_terms < term.date:
356 self.has_signed_terms = False
357 self.date_signed_terms = None
362 class Membership(models.Model):
363 person = models.ForeignKey(AstakosUser)
364 group = models.ForeignKey(AstakosGroup)
365 date_requested = models.DateField(default=datetime.now(), blank=True)
366 date_joined = models.DateField(null=True, db_index=True, blank=True)
369 unique_together = ("person", "group")
371 def save(self, *args, **kwargs):
373 if not self.group.moderation_enabled:
374 self.date_joined = datetime.now()
375 super(Membership, self).save(*args, **kwargs)
378 def is_approved(self):
384 self.date_joined = datetime.now()
387 def disapprove(self):
390 class AstakosGroupQuota(models.Model):
391 limit = models.PositiveIntegerField('Limit')
392 resource = models.ForeignKey(Resource)
393 group = models.ForeignKey(AstakosGroup, blank=True)
396 unique_together = ("resource", "group")
398 class AstakosUserQuota(models.Model):
399 limit = models.PositiveIntegerField('Limit')
400 resource = models.ForeignKey(Resource)
401 user = models.ForeignKey(AstakosUser)
404 unique_together = ("resource", "user")
406 class ApprovalTerms(models.Model):
408 Model for approval terms
411 date = models.DateTimeField('Issue date', db_index=True, default=datetime.now())
412 location = models.CharField('Terms location', max_length=255)
414 class Invitation(models.Model):
416 Model for registring invitations
418 inviter = models.ForeignKey(AstakosUser, related_name='invitations_sent',
420 realname = models.CharField('Real name', max_length=255)
421 username = models.CharField('Unique ID', max_length=255, unique=True)
422 code = models.BigIntegerField('Invitation code', db_index=True)
423 is_consumed = models.BooleanField('Consumed?', default=False)
424 created = models.DateTimeField('Creation date', auto_now_add=True)
425 consumed = models.DateTimeField('Consumption date', null=True, blank=True)
427 def __init__(self, *args, **kwargs):
428 super(Invitation, self).__init__(*args, **kwargs)
430 self.code = _generate_invitation_code()
433 self.is_consumed = True
434 self.consumed = datetime.now()
437 def __unicode__(self):
438 return '%s -> %s [%d]' % (self.inviter, self.username, self.code)
440 def report_user_event(user):
441 def should_send(user):
442 # report event incase of new user instance
443 # or if specific fields are modified
447 db_instance = AstakosUser.objects.get(id = user.id)
448 except AstakosUser.DoesNotExist:
450 for f in BILLING_FIELDS:
451 if (db_instance.__getattribute__(f) != user.__getattribute__(f)):
455 if QUEUE_CONNECTION and should_send(user):
457 from astakos.im.queue.userevent import UserEvent
458 from synnefo.lib.queue import exchange_connect, exchange_send, \
461 eventType = 'create' if not user.id else 'modify'
462 body = UserEvent(QUEUE_CLIENT_ID, user, eventType, {}).format()
463 conn = exchange_connect(QUEUE_CONNECTION)
464 parts = urlparse(QUEUE_CONNECTION)
465 exchange = parts.path[1:]
466 routing_key = '%s.user' % exchange
467 exchange_send(conn, routing_key, body)
470 def _generate_invitation_code():
472 code = randint(1, 2L**63 - 1)
474 Invitation.objects.get(code=code)
475 # An invitation with this code already exists, try again
476 except Invitation.DoesNotExist:
479 def get_latest_terms():
481 term = ApprovalTerms.objects.order_by('-id')[0]
487 class EmailChangeManager(models.Manager):
488 @transaction.commit_on_success
489 def change_email(self, activation_key):
491 Validate an activation key and change the corresponding
494 If the key is valid and has not expired, return the ``User``
497 If the key is not valid or has expired, return ``None``.
499 If the key is valid but the ``User`` is already active,
502 After successful email change the activation record is deleted.
504 Throws ValueError if there is already
507 email_change = self.model.objects.get(activation_key=activation_key)
508 if email_change.activation_key_expired():
509 email_change.delete()
510 raise EmailChange.DoesNotExist
511 # is there an active user with this address?
513 AstakosUser.objects.get(email=email_change.new_email_address)
514 except AstakosUser.DoesNotExist:
517 raise ValueError(_('The new email address is reserved.'))
519 user = AstakosUser.objects.get(pk=email_change.user_id)
520 user.email = email_change.new_email_address
522 email_change.delete()
524 except EmailChange.DoesNotExist:
525 raise ValueError(_('Invalid activation key'))
527 class EmailChange(models.Model):
528 new_email_address = models.EmailField(_(u'new e-mail address'), help_text=_(u'Your old email address will be used until you verify your new one.'))
529 user = models.ForeignKey(AstakosUser, unique=True, related_name='emailchange_user')
530 requested_at = models.DateTimeField(default=datetime.now())
531 activation_key = models.CharField(max_length=40, unique=True, db_index=True)
533 objects = EmailChangeManager()
535 def activation_key_expired(self):
536 expiration_date = timedelta(days=EMAILCHANGE_ACTIVATION_DAYS)
537 return self.requested_at + expiration_date < datetime.now()
539 class AdditionalMail(models.Model):
541 Model for registring invitations
543 owner = models.ForeignKey(AstakosUser)
544 email = models.EmailField()
546 def create_astakos_user(u):
548 AstakosUser.objects.get(user_ptr=u.pk)
549 except AstakosUser.DoesNotExist:
550 extended_user = AstakosUser(user_ptr_id=u.pk)
551 extended_user.__dict__.update(u.__dict__)
552 extended_user.renew_token()
557 def superuser_post_syncdb(sender, **kwargs):
558 # if there was created a superuser
559 # associate it with an AstakosUser
560 admins = User.objects.filter(is_superuser=True)
562 create_astakos_user(u)
564 post_syncdb.connect(superuser_post_syncdb)
566 def superuser_post_save(sender, instance, **kwargs):
567 if instance.is_superuser:
568 create_astakos_user(instance)
570 post_save.connect(superuser_post_save, sender=User)