models.py 6.82 KB
Newer Older
Antony Chazapis's avatar
Antony Chazapis committed
1
# Copyright 2011-2012 GRNET S.A. All rights reserved.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
# 
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
# 
#   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.
# 
# 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.
# 
# 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
36
37
38
39
40
41

from time import asctime
from datetime import datetime, timedelta
from base64 import b64encode

from django.db import models
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
42
from django.contrib.auth.models import User, UserManager
43

44
45
46
47
from astakos.im.settings import DEFAULT_USER_LEVEL, INVITATIONS_PER_LEVEL, AUTH_TOKEN_DURATION, BILLING_FIELDS, QUEUE_CONNECTION
from synnefo.lib.queue import exchange_connect, exchange_send, exchange_close, Receipt

QUEUE_CLIENT_ID = 3 # Astakos.
48

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
49
class AstakosUser(User):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
50
51
52
    """
    Extends ``django.contrib.auth.models.User`` by defining additional fields.
    """
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
53
54
    # Use UserManager to get the create_user method, etc.
    objects = UserManager()
55
    
56
57
    affiliation = models.CharField('Affiliation', max_length=255, blank=True)
    provider = models.CharField('Provider', max_length=255, blank=True)
58
59
    
    #for invitations
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
60
    user_level = DEFAULT_USER_LEVEL
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
61
    level = models.IntegerField('Inviter level', default=user_level)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
62
    invitations = models.IntegerField('Invitations left', default=INVITATIONS_PER_LEVEL[user_level])
63
64
    
    auth_token = models.CharField('Authentication Token', max_length=32,
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
65
66
67
                                  null=True, blank=True)
    auth_token_created = models.DateTimeField('Token creation date', null=True)
    auth_token_expires = models.DateTimeField('Token expiration date', null=True)
68
69
    
    updated = models.DateTimeField('Update date')
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
70
    is_verified = models.BooleanField('Is verified?', default=False)
71
    
72
73
74
    # ex. screen_name for twitter, eppn for shibboleth
    third_party_identifier = models.CharField('Third-party identifier', max_length=255, null=True, blank=True)
    
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
75
76
77
    @property
    def realname(self):
        return '%s %s' %(self.first_name, self.last_name)
78
    
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
79
80
81
82
83
84
85
86
    @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]
87
88
89
90
    
    @property
    def invitation(self):
        try:
91
            return Invitation.objects.get(username=self.email)
92
93
94
95
96
97
        except Invitation.DoesNotExist:
            return None
    
    def save(self, update_timestamps=True, **kwargs):
        if update_timestamps:
            if not self.id:
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
98
                self.date_joined = datetime.now()
99
            self.updated = datetime.now()
100
101
102
103
104
105
106
107
108
109
110
111
        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
            self.is_active = False
            if not self.provider:
                self.provider = 'local'
        report_user_event(self)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
112
        super(AstakosUser, self).save(**kwargs)
113
114
115
    
    def renew_token(self):
        md5 = hashlib.md5()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
116
        md5.update(self.username)
117
118
119
120
121
122
        md5.update(self.realname.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 + \
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
123
                                  timedelta(hours=AUTH_TOKEN_DURATION)
124
125
    
    def __unicode__(self):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
126
        return self.username
127
128

class Invitation(models.Model):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
129
130
131
    """
    Model for registring invitations
    """
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
132
    inviter = models.ForeignKey(AstakosUser, related_name='invitations_sent',
133
134
                                null=True)
    realname = models.CharField('Real name', max_length=255)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
135
    username = models.CharField('Unique ID', max_length=255)
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
    code = models.BigIntegerField('Invitation code', db_index=True)
    #obsolete: we keep it just for transfering the data
    is_accepted = models.BooleanField('Accepted?', default=False)
    is_consumed = models.BooleanField('Consumed?', default=False)
    created = models.DateTimeField('Creation date', auto_now_add=True)
    #obsolete: we keep it just for transfering the data
    accepted = models.DateTimeField('Acceptance date', null=True, blank=True)
    consumed = models.DateTimeField('Consumption date', null=True, blank=True)
    
    def consume(self):
        self.is_consumed = True
        self.consumed = datetime.now()
        self.save()
        
    def __unicode__(self):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
151
        return '%s -> %s [%d]' % (self.inviter, self.username, self.code)
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174

def report_user_event(user):
    def should_send(user):
        # report event incase of new user instance
        # or if specific fields are modified
        if not user.id:
            return True
        db_instance = AstakosUser.objects.get(id = user.id)
        for f in BILLING_FIELDS:
            if (db_instance.__getattribute__(f) != user.__getattribute__(f)):
                return True
        return False
    
    if QUEUE_CONNECTION and should_send(user):
        l = [[elem, str(user.__getattribute__(elem))] for elem in BILLING_FIELDS]
        details = dict(l)
        body = Receipt(QUEUE_CLIENT_ID, user.email, '', 0, details).format()
        msgsubtype = 'create' if not user.id else 'modify'
        exchange = '%s.%s.#' %(QUEUE_CONNECTION, msgsubtype)
        conn = exchange_connect(exchange)
        routing_key = exchange.replace('#', body['id'])
        exchange_send(conn, routing_key, body)
        exchange_close(conn)