Revision 49790d9d snf-astakos-app/astakos/im/models.py

b/snf-astakos-app/astakos/im/models.py
42 42
from urlparse import urlparse, urlunparse
43 43
from random import randint
44 44

  
45
from django.db import models
45
from django.db import models, IntegrityError
46 46
from django.contrib.auth.models import User, UserManager, Group
47 47
from django.utils.translation import ugettext as _
48 48
from django.core.exceptions import ValidationError
49
from django.template.loader import render_to_string
50
from django.core.mail import send_mail
51
from django.db import transaction
49 52

  
50
from astakos.im.settings import DEFAULT_USER_LEVEL, INVITATIONS_PER_LEVEL, AUTH_TOKEN_DURATION, BILLING_FIELDS, QUEUE_CONNECTION
53
from astakos.im.settings import DEFAULT_USER_LEVEL, INVITATIONS_PER_LEVEL, \
54
AUTH_TOKEN_DURATION, BILLING_FIELDS, QUEUE_CONNECTION, SITENAME, \
55
EMAILCHANGE_ACTIVATION_DAYS
51 56

  
52 57
QUEUE_CLIENT_ID = 3 # Astakos.
53 58

  
......
270 275
        return term
271 276
    except IndexError:
272 277
        pass
273
    return None
278
    return None
279

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

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

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

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

  
295
        After successful email change the activation record is deleted.
296

  
297
        Throws ValueError if there is already
298
        """
299
        try:
300
            email_change = self.model.objects.get(activation_key=activation_key)
301
            if email_change.activation_key_expired():
302
                email_change.delete()
303
                raise EmailChange.DoesNotExist
304
            # is there an active user with this address?
305
            try:
306
                AstakosUser.objects.get(email=email_change.new_email_address)
307
            except AstakosUser.DoesNotExist:
308
                pass
309
            else:
310
                raise ValueError(_('The new email address is reserved.'))
311
            # update user
312
            user = AstakosUser.objects.get(pk=email_change.user_id)
313
            user.email = email_change.new_email_address
314
            user.save()
315
            email_change.delete()
316
            return user
317
        except EmailChange.DoesNotExist:
318
            raise ValueError(_('Invalid activation key'))
319

  
320
class EmailChange(models.Model):
321
    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.'))
322
    user = models.ForeignKey(AstakosUser, unique=True, related_name='emailchange_user')
323
    requested_at = models.DateTimeField(default=datetime.now())
324
    activation_key = models.CharField(max_length=40, unique=True, db_index=True)
325

  
326
    objects = EmailChangeManager()
327

  
328
    def activation_key_expired(self):
329
        expiration_date = timedelta(days=EMAILCHANGE_ACTIVATION_DAYS)
330
        return self.requested_at + expiration_date < datetime.now()

Also available in: Unified diff