root / snf-astakos-app / astakos / im / models.py @ 8f5a3a06
History | View | Annotate | Download (7.8 kB)
1 |
# Copyright 2011-2012 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 hashlib |
35 |
import uuid |
36 |
|
37 |
from time import asctime |
38 |
from datetime import datetime, timedelta |
39 |
from base64 import b64encode |
40 |
from urlparse import urlparse |
41 |
from random import randint |
42 |
|
43 |
from django.db import models |
44 |
from django.contrib.auth.models import User, UserManager |
45 |
|
46 |
from astakos.im.settings import DEFAULT_USER_LEVEL, INVITATIONS_PER_LEVEL, AUTH_TOKEN_DURATION, BILLING_FIELDS, QUEUE_CONNECTION |
47 |
from astakos.im.queue.userevent import UserEvent |
48 |
from synnefo.lib.queue import exchange_connect, exchange_send, exchange_close, Receipt |
49 |
|
50 |
QUEUE_CLIENT_ID = 3 # Astakos. |
51 |
|
52 |
class AstakosUser(User): |
53 |
"""
|
54 |
Extends ``django.contrib.auth.models.User`` by defining additional fields.
|
55 |
"""
|
56 |
# Use UserManager to get the create_user method, etc.
|
57 |
objects = UserManager() |
58 |
|
59 |
affiliation = models.CharField('Affiliation', max_length=255, blank=True) |
60 |
provider = models.CharField('Provider', max_length=255, blank=True) |
61 |
|
62 |
#for invitations
|
63 |
user_level = DEFAULT_USER_LEVEL |
64 |
level = models.IntegerField('Inviter level', default=user_level)
|
65 |
invitations = models.IntegerField('Invitations left', default=INVITATIONS_PER_LEVEL.get(user_level, 0)) |
66 |
|
67 |
auth_token = models.CharField('Authentication Token', max_length=32, |
68 |
null=True, blank=True) |
69 |
auth_token_created = models.DateTimeField('Token creation date', null=True) |
70 |
auth_token_expires = models.DateTimeField('Token expiration date', null=True) |
71 |
|
72 |
updated = models.DateTimeField('Update date')
|
73 |
is_verified = models.BooleanField('Is verified?', default=False) |
74 |
|
75 |
# ex. screen_name for twitter, eppn for shibboleth
|
76 |
third_party_identifier = models.CharField('Third-party identifier', max_length=255, null=True, blank=True) |
77 |
|
78 |
email_verified = models.BooleanField('Email verified?', default=False) |
79 |
|
80 |
has_credits = models.BooleanField('Has credits?', default=False) |
81 |
has_signed_terms = models.BooleanField('Agree with the terms?', default=False) |
82 |
date_signed_terms = models.DateTimeField('Signed terms date', null=True) |
83 |
|
84 |
@property
|
85 |
def realname(self): |
86 |
return '%s %s' %(self.first_name, self.last_name) |
87 |
|
88 |
@realname.setter
|
89 |
def realname(self, value): |
90 |
parts = value.split(' ')
|
91 |
if len(parts) == 2: |
92 |
self.first_name = parts[0] |
93 |
self.last_name = parts[1] |
94 |
else:
|
95 |
self.last_name = parts[0] |
96 |
|
97 |
@property
|
98 |
def invitation(self): |
99 |
try:
|
100 |
return Invitation.objects.get(username=self.email) |
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.date_joined = datetime.now()
|
108 |
self.updated = datetime.now()
|
109 |
if not self.id: |
110 |
# set username
|
111 |
while not self.username: |
112 |
username = uuid.uuid4().hex[:30]
|
113 |
try:
|
114 |
AstakosUser.objects.get(username = username) |
115 |
except AstakosUser.DoesNotExist, e:
|
116 |
self.username = username
|
117 |
self.is_active = False |
118 |
if not self.provider: |
119 |
self.provider = 'local' |
120 |
report_user_event(self)
|
121 |
super(AstakosUser, self).save(**kwargs) |
122 |
|
123 |
def renew_token(self): |
124 |
md5 = hashlib.md5() |
125 |
md5.update(self.username)
|
126 |
md5.update(self.realname.encode('ascii', 'ignore')) |
127 |
md5.update(asctime()) |
128 |
|
129 |
self.auth_token = b64encode(md5.digest())
|
130 |
self.auth_token_created = datetime.now()
|
131 |
self.auth_token_expires = self.auth_token_created + \ |
132 |
timedelta(hours=AUTH_TOKEN_DURATION) |
133 |
|
134 |
def __unicode__(self): |
135 |
return self.username |
136 |
|
137 |
class ApprovalTerms(models.Model): |
138 |
"""
|
139 |
Model for approval terms
|
140 |
"""
|
141 |
|
142 |
date = models.DateTimeField('Issue date', db_index=True, default=datetime.now()) |
143 |
location = models.CharField('Terms location', max_length=255) |
144 |
|
145 |
class Invitation(models.Model): |
146 |
"""
|
147 |
Model for registring invitations
|
148 |
"""
|
149 |
inviter = models.ForeignKey(AstakosUser, related_name='invitations_sent',
|
150 |
null=True)
|
151 |
realname = models.CharField('Real name', max_length=255) |
152 |
username = models.CharField('Unique ID', max_length=255, unique=True) |
153 |
code = models.BigIntegerField('Invitation code', db_index=True) |
154 |
#obsolete: we keep it just for transfering the data
|
155 |
is_accepted = models.BooleanField('Accepted?', default=False) |
156 |
is_consumed = models.BooleanField('Consumed?', default=False) |
157 |
created = models.DateTimeField('Creation date', auto_now_add=True) |
158 |
#obsolete: we keep it just for transfering the data
|
159 |
accepted = models.DateTimeField('Acceptance date', null=True, blank=True) |
160 |
consumed = models.DateTimeField('Consumption date', null=True, blank=True) |
161 |
|
162 |
def save(self, **kwargs): |
163 |
if not self.id: |
164 |
self.code = _generate_invitation_code()
|
165 |
super(Invitation, self).save(**kwargs) |
166 |
|
167 |
def consume(self): |
168 |
self.is_consumed = True |
169 |
self.consumed = datetime.now()
|
170 |
self.save()
|
171 |
|
172 |
def __unicode__(self): |
173 |
return '%s -> %s [%d]' % (self.inviter, self.username, self.code) |
174 |
|
175 |
def report_user_event(user): |
176 |
def should_send(user): |
177 |
# report event incase of new user instance
|
178 |
# or if specific fields are modified
|
179 |
if not user.id: |
180 |
return True |
181 |
db_instance = AstakosUser.objects.get(id = user.id) |
182 |
for f in BILLING_FIELDS: |
183 |
if (db_instance.__getattribute__(f) != user.__getattribute__(f)):
|
184 |
return True |
185 |
return False |
186 |
|
187 |
if QUEUE_CONNECTION and should_send(user): |
188 |
eventType = 'create' if not user.id else 'modify' |
189 |
body = UserEvent(QUEUE_CLIENT_ID, user, eventType, {}).format() |
190 |
conn = exchange_connect(QUEUE_CONNECTION) |
191 |
parts = urlparse(QUEUE_CONNECTION) |
192 |
exchange = parts.path[1:]
|
193 |
routing_key = '%s.user' % exchange
|
194 |
exchange_send(conn, routing_key, body) |
195 |
exchange_close(conn) |
196 |
|
197 |
def _generate_invitation_code(): |
198 |
while True: |
199 |
code = randint(1, 2L**63 - 1) |
200 |
try:
|
201 |
Invitation.objects.get(code=code) |
202 |
# An invitation with this code already exists, try again
|
203 |
except Invitation.DoesNotExist:
|
204 |
return code
|