Initial commit. Move from pithos repository.
[astakos] / astakos / im / models.py
1 # Copyright 2011 GRNET S.A. All rights reserved.
2
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
5 # conditions are met:
6
7 #   1. Redistributions of source code must retain the above
8 #      copyright notice, this list of conditions and the following
9 #      disclaimer.
10
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.
15
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.
28
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.
33
34 import logging
35 import hashlib
36
37 from time import asctime
38 from datetime import datetime, timedelta
39 from base64 import b64encode
40
41 from django.conf import settings
42 from django.db import models
43
44 from astakos.im.interface import get_quota, set_quota
45
46 from hashlib import new as newhasher
47
48 class User(models.Model):
49     ACCOUNT_STATE = (
50         ('ACTIVE', 'Active'),
51         ('DELETED', 'Deleted'),
52         ('SUSPENDED', 'Suspended'),
53         ('UNVERIFIED', 'Unverified'),
54         ('PENDING', 'Pending')
55     )
56     
57     uniq = models.CharField('Unique ID', max_length=255, null=True)
58     
59     realname = models.CharField('Real Name', max_length=255, default='')
60     email = models.CharField('Email', max_length=255, default='')
61     affiliation = models.CharField('Affiliation', max_length=255, default='')
62     provider = models.CharField('Provider', max_length=255, default='')
63     state = models.CharField('Account state', choices=ACCOUNT_STATE,
64                                 max_length=16, default='PENDING')
65     
66     #for invitations
67     level = models.IntegerField('Inviter level', default=4)
68     invitations = models.IntegerField('Invitations left', default=0)
69     
70     #for local
71     password = models.CharField('Password', max_length=255, default='')
72     
73     is_admin = models.BooleanField('Admin?', default=False)
74     
75     auth_token = models.CharField('Authentication Token', max_length=32,
76                                     null=True, blank=True)
77     auth_token_created = models.DateTimeField('Token creation date',
78                                                 null=True)
79     auth_token_expires = models.DateTimeField('Token expiration date',
80                                                 null=True)
81     
82     created = models.DateTimeField('Creation date')
83     updated = models.DateTimeField('Update date')
84     
85     is_verified = models.BooleanField('Verified?', default=False)
86     
87     openidurl = models.CharField('OpenID url', max_length=255, default='')
88     
89     @property
90     def quota(self):
91         return get_quota(self.uniq)
92
93     @quota.setter
94     def quota(self, value):
95         set_quota(self.uniq, value)
96     
97     @property
98     def invitation(self):
99         try:
100             return Invitation.objects.get(uniq=self.uniq)
101         except Invitation.DoesNotExist:
102             return None
103     
104     def save(self, update_timestamps=True, **kwargs):
105         if update_timestamps:
106             if not self.id:
107                 self.created = datetime.now()
108             self.updated = datetime.now()
109         
110         super(User, self).save(**kwargs)
111         
112         #invitation consume
113         if self.invitation and not self.invitation.is_consumed:
114             self.invitation.consume()
115     
116     def renew_token(self):
117         md5 = hashlib.md5()
118         md5.update(self.uniq)
119         md5.update(self.realname.encode('ascii', 'ignore'))
120         md5.update(asctime())
121         
122         self.auth_token = b64encode(md5.digest())
123         self.auth_token_created = datetime.now()
124         self.auth_token_expires = self.auth_token_created + \
125                                   timedelta(hours=settings.AUTH_TOKEN_DURATION)
126     
127     def __unicode__(self):
128         return self.uniq
129
130 class Invitation(models.Model):
131     inviter = models.ForeignKey(User, related_name='invitations_sent',
132                                 null=True)
133     realname = models.CharField('Real name', max_length=255)
134     uniq = models.CharField('Unique ID', max_length=255)
135     code = models.BigIntegerField('Invitation code', db_index=True)
136     #obsolete: we keep it just for transfering the data
137     is_accepted = models.BooleanField('Accepted?', default=False)
138     is_consumed = models.BooleanField('Consumed?', default=False)
139     created = models.DateTimeField('Creation date', auto_now_add=True)
140     #obsolete: we keep it just for transfering the data
141     accepted = models.DateTimeField('Acceptance date', null=True, blank=True)
142     consumed = models.DateTimeField('Consumption date', null=True, blank=True)
143     
144     def consume(self):
145         self.is_consumed = True
146         self.consumed = datetime.now()
147         self.save()
148         
149     def __unicode__(self):
150         return '%s -> %s [%d]' % (self.inviter, self.uniq, self.code)