root / invitations / invitations.py @ 0fbab7db
History | View | Annotate | Download (10.6 kB)
1 |
# vim: set fileencoding=utf-8 :
|
---|---|
2 |
# Copyright 2011 GRNET S.A. All rights reserved.
|
3 |
#
|
4 |
# Redistribution and use in source and binary forms, with or without
|
5 |
# modification, are permitted provided that the following conditions
|
6 |
# are met:
|
7 |
#
|
8 |
# 1. Redistributions of source code must retain the above copyright
|
9 |
# notice, this list of conditions and the following disclaimer.
|
10 |
#
|
11 |
# 2. Redistributions in binary form must reproduce the above copyright
|
12 |
# notice, this list of conditions and the following disclaimer in the
|
13 |
# documentation and/or other materials provided with the distribution.
|
14 |
#
|
15 |
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
|
16 |
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
17 |
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
18 |
# ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
|
19 |
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
20 |
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
|
21 |
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
|
22 |
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
23 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
24 |
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
25 |
# SUCH DAMAGE.
|
26 |
#
|
27 |
# The views and conclusions contained in the software and documentation are
|
28 |
# those of the authors and should not be interpreted as representing official
|
29 |
# policies, either expressed or implied, of GRNET S.A.
|
30 |
|
31 |
|
32 |
from datetime import timedelta |
33 |
import datetime |
34 |
import base64 |
35 |
import time |
36 |
import urllib |
37 |
|
38 |
from django.conf import settings |
39 |
from django.core.exceptions import ValidationError |
40 |
from django.db import transaction |
41 |
from django.http import HttpResponse, HttpResponseRedirect |
42 |
from django.template.context import RequestContext |
43 |
from django.template.loader import render_to_string |
44 |
from django.core.validators import validate_email |
45 |
from django.views.decorators.csrf import csrf_protect |
46 |
from django.utils.translation import ugettext as _ |
47 |
|
48 |
from synnefo.logic.email_send import send_async |
49 |
from synnefo.api.common import method_not_allowed |
50 |
from synnefo.db.models import Invitations, SynnefoUser |
51 |
from synnefo.logic import users, log |
52 |
|
53 |
from Crypto.Cipher import AES |
54 |
|
55 |
_logger = log.get_logger("synnefo.invitations")
|
56 |
|
57 |
def process_form(request): |
58 |
errors = [] |
59 |
valid_inv = filter(lambda x: x.startswith("name_"), request.POST.keys()) |
60 |
|
61 |
for inv in valid_inv: |
62 |
(name, inv_id) = inv.split('_')
|
63 |
|
64 |
email = ""
|
65 |
name = ""
|
66 |
try:
|
67 |
email = request.POST['email_' + inv_id]
|
68 |
name = request.POST[inv] |
69 |
|
70 |
validate_name(name) |
71 |
validate_email(email) |
72 |
|
73 |
inv = add_invitation(request.user, name, email) |
74 |
send_invitation(inv) |
75 |
|
76 |
# FIXME: Delete invitation and user on error
|
77 |
except (InvitationException, ValidationError) as e: |
78 |
errors += ["Invitation to %s <%s> not sent. Reason: %s" %
|
79 |
(name, email, e.messages[0])]
|
80 |
except Exception as e: |
81 |
_logger.exception(e) |
82 |
errors += ["Invitation to %s <%s> not sent. Reason: %s" %
|
83 |
(name, email, e.message)] |
84 |
|
85 |
respose = None
|
86 |
if errors:
|
87 |
data = render_to_string('invitations.html',
|
88 |
{'invitations': invitations_for_user(request),
|
89 |
'errors': errors,
|
90 |
'invitations_left': get_invitations_left(request.user)
|
91 |
}, |
92 |
context_instance=RequestContext(request)) |
93 |
response = HttpResponse(data) |
94 |
_logger.warn("Error adding invitation %s -> %s: %s"%(request.user.uniq,
|
95 |
email, errors)) |
96 |
else:
|
97 |
# form submitted
|
98 |
data = render_to_string('invitations.html',
|
99 |
{'invitations': invitations_for_user(request),
|
100 |
'invitations_left': get_invitations_left(request.user)
|
101 |
}, |
102 |
context_instance=RequestContext(request)) |
103 |
response = HttpResponse(data) |
104 |
_logger.info("Added invitation %s -> %s"%(request.user.uniq, email))
|
105 |
|
106 |
return response
|
107 |
|
108 |
|
109 |
def validate_name(name): |
110 |
if name is None or name.strip() == '': |
111 |
raise ValidationError("Name is empty") |
112 |
|
113 |
if name.find(' ') is -1: |
114 |
raise ValidationError(_("Name must contain at least one space")) |
115 |
|
116 |
return True |
117 |
|
118 |
|
119 |
def invitations_for_user(request): |
120 |
invitations = [] |
121 |
|
122 |
for inv in Invitations.objects.filter(source = request.user): |
123 |
invitation = {} |
124 |
|
125 |
invitation['sourcename'] = inv.source.realname
|
126 |
invitation['source'] = inv.source.uniq
|
127 |
invitation['targetname'] = inv.target.realname
|
128 |
invitation['target'] = inv.target.uniq
|
129 |
invitation['accepted'] = inv.accepted
|
130 |
invitation['sent'] = inv.created
|
131 |
|
132 |
invitations.append(invitation) |
133 |
|
134 |
return invitations
|
135 |
|
136 |
|
137 |
@csrf_protect
|
138 |
def inv_demux(request): |
139 |
|
140 |
if request.method == 'GET': |
141 |
data = render_to_string('invitations.html',
|
142 |
{'invitations': invitations_for_user(request),
|
143 |
'invitations_left': get_invitations_left(request.user)
|
144 |
}, |
145 |
context_instance=RequestContext(request)) |
146 |
return HttpResponse(data)
|
147 |
elif request.method == 'POST': |
148 |
return process_form(request)
|
149 |
else:
|
150 |
method_not_allowed(request) |
151 |
|
152 |
|
153 |
def login(request): |
154 |
|
155 |
if not request.method == 'GET': |
156 |
method_not_allowed(request) |
157 |
|
158 |
key = request.GET['key']
|
159 |
|
160 |
if key is None: |
161 |
return render_login_error("10", "Required key is missing") |
162 |
|
163 |
PADDING = '{'
|
164 |
|
165 |
try:
|
166 |
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
|
167 |
cipher = AES.new(settings.INVITATION_ENCR_KEY) |
168 |
decoded = DecodeAES(cipher, key) |
169 |
except Exception: |
170 |
return render_login_error("20", "Required key is invalid") |
171 |
|
172 |
users = SynnefoUser.objects.filter(auth_token = decoded) |
173 |
|
174 |
if users.count() is 0: |
175 |
return render_login_error("20", "Required key is invalid") |
176 |
|
177 |
user = users[0]
|
178 |
invitations = Invitations.objects.filter(target = user) |
179 |
|
180 |
if invitations.count() is 0: |
181 |
return render_login_error("30", "Non-existent invitation") |
182 |
|
183 |
inv = invitations[0]
|
184 |
|
185 |
valid = timedelta(days=settings.INVITATION_VALID_DAYS) |
186 |
valid_until = inv.created + valid |
187 |
now = datetime.datetime.now() |
188 |
|
189 |
if now > valid_until:
|
190 |
return render_login_error("40", |
191 |
"Invitation has expired (was valid until " \
|
192 |
"%s, now is %s" %
|
193 |
(valid_until.strftime('%A, %d %B %Y'),
|
194 |
now.strftime('%A, %d %B %Y')))
|
195 |
|
196 |
#if inv.accepted == False:
|
197 |
# return render_login_error("60", "Invitation already accepted")
|
198 |
|
199 |
inv.accepted = True
|
200 |
inv.save() |
201 |
|
202 |
_logger.info("Invited user %s logged in"%(inv.target.uniq))
|
203 |
|
204 |
data = dict()
|
205 |
data['user'] = user.realname
|
206 |
data['url'] = settings.APP_INSTALL_URL
|
207 |
|
208 |
welcome = render_to_string('welcome.html', {'data': data}) |
209 |
|
210 |
response = HttpResponse(welcome) |
211 |
|
212 |
response.set_cookie('X-Auth-Token', value=user.auth_token,
|
213 |
expires = valid_until.strftime('%a, %d-%b-%Y %H:%M:%S %Z'),
|
214 |
path='/')
|
215 |
response['X-Auth-Token'] = user.auth_token
|
216 |
return response
|
217 |
|
218 |
|
219 |
def render_login_error(code, text): |
220 |
error = dict()
|
221 |
error['id'] = code
|
222 |
error['text'] = text
|
223 |
|
224 |
data = render_to_string('error.html', {'error': error}) |
225 |
|
226 |
response = HttpResponse(data) |
227 |
return response
|
228 |
|
229 |
|
230 |
def send_invitation(invitation): |
231 |
email = {} |
232 |
email['invitee'] = invitation.target.realname
|
233 |
email['inviter'] = invitation.source.realname
|
234 |
|
235 |
valid = timedelta(days = settings.INVITATION_VALID_DAYS) |
236 |
valid_until = invitation.created + valid |
237 |
email['valid_until'] = valid_until.strftime('%A, %d %B %Y') |
238 |
|
239 |
PADDING = '{'
|
240 |
pad = lambda s: s + (32 - len(s) % 32) * PADDING |
241 |
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
|
242 |
|
243 |
cipher = AES.new(settings.INVITATION_ENCR_KEY) |
244 |
encoded = EncodeAES(cipher, invitation.target.auth_token) |
245 |
|
246 |
url_safe = urllib.urlencode({'key': encoded})
|
247 |
|
248 |
email['url'] = settings.APP_INSTALL_URL + "/invitations/login?" + url_safe |
249 |
|
250 |
data = render_to_string('invitation.txt', {'email': email}) |
251 |
|
252 |
_logger.debug("Invitation URL: %s" % email['url']) |
253 |
|
254 |
send_async( |
255 |
frm = "%s"%(settings.DEFAULT_FROM_EMAIL),
|
256 |
to = "%s <%s>"%(invitation.target.realname,invitation.target.uniq),
|
257 |
subject = _('Invitation to ~okeanos IaaS service'),
|
258 |
body = data |
259 |
) |
260 |
|
261 |
def get_invitee_level(source): |
262 |
return get_user_inv_level(source) + 1 |
263 |
|
264 |
|
265 |
def get_user_inv_level(u): |
266 |
inv = Invitations.objects.filter(target = u) |
267 |
|
268 |
if not inv: |
269 |
raise Exception("User without invitation", u) |
270 |
|
271 |
return inv[0].level |
272 |
|
273 |
|
274 |
@transaction.commit_on_success
|
275 |
def add_invitation(source, name, email): |
276 |
"""
|
277 |
Adds an invitation, if the source user has not gone over his/her
|
278 |
invitation limit or the target user has not been invited already
|
279 |
"""
|
280 |
num_inv = Invitations.objects.filter(source = source).count() |
281 |
|
282 |
if num_inv >= source.max_invitations:
|
283 |
raise TooManyInvitations("User invitation limit (%d) exhausted" % |
284 |
source.max_invitations) |
285 |
|
286 |
target = SynnefoUser.objects.filter(uniq = email) |
287 |
|
288 |
if target.count() is not 0: |
289 |
raise AlreadyInvited("User with email %s already invited" % (email)) |
290 |
|
291 |
users.register_user(name, email) |
292 |
|
293 |
target = SynnefoUser.objects.filter(uniq = email) |
294 |
|
295 |
r = list(target[:1]) |
296 |
if not r: |
297 |
raise Exception("Invited user cannot be added") |
298 |
|
299 |
u = target[0]
|
300 |
invitee_level = get_invitee_level(source) |
301 |
|
302 |
u.max_invitations = settings.INVITATIONS_PER_LEVEL[invitee_level] |
303 |
u.save() |
304 |
|
305 |
inv = Invitations() |
306 |
inv.source = source |
307 |
inv.target = u |
308 |
inv.level = invitee_level |
309 |
inv.save() |
310 |
return inv
|
311 |
|
312 |
|
313 |
@transaction.commit_on_success
|
314 |
def invitation_accepted(invitation): |
315 |
"""
|
316 |
Mark an invitation as accepted
|
317 |
"""
|
318 |
invitation.accepted = True
|
319 |
invitation.save() |
320 |
|
321 |
|
322 |
def get_invitations_left(user): |
323 |
"""
|
324 |
Get user invitations left
|
325 |
"""
|
326 |
num_inv = Invitations.objects.filter(source = user).count() |
327 |
return user.max_invitations - num_inv
|
328 |
|
329 |
class InvitationException(Exception): |
330 |
def __init__(self, msg): |
331 |
self.messages = [msg]
|
332 |
|
333 |
class TooManyInvitations(InvitationException): |
334 |
pass
|
335 |
|
336 |
class AlreadyInvited(InvitationException): |
337 |
pass
|