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