1 # Copyright 2011-2012 GRNET S.A. All rights reserved.
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
7 # 1. Redistributions of source code must retain the above
8 # copyright notice, this list of conditions and the following
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.
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.
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.
38 from urllib import quote
39 from urlparse import urlsplit, urlunsplit
40 from functools import wraps
42 from datetime import tzinfo, timedelta
43 from django.http import HttpResponse, HttpResponseBadRequest, urlencode
44 from django.template import RequestContext
45 from django.utils.translation import ugettext as _
46 from django.contrib.auth import login, authenticate
47 from django.core.urlresolvers import reverse
48 from django.core.exceptions import ValidationError
50 from astakos.im.models import AstakosUser, Invitation, ApprovalTerms
51 from astakos.im.settings import INVITATIONS_PER_LEVEL, COOKIE_NAME, COOKIE_DOMAIN, COOKIE_SECURE, FORCE_PROFILE_UPDATE
53 logger = logging.getLogger(__name__)
56 def utcoffset(self, dt):
66 """Return an ISO8601 date string that includes a timezone."""
68 return d.replace(tzinfo=UTC()).isoformat()
71 return int(time.mktime(datetime.timetuple())*1000)
73 def get_context(request, extra_context={}, **kwargs):
76 extra_context.update(kwargs)
77 return RequestContext(request, extra_context)
79 def get_invitation(request):
81 Returns the invitation identified by the ``code``.
83 Raises ValueError if the invitation is consumed or there is another account
84 associated with this email.
86 code = request.GET.get('code')
87 if request.method == 'POST':
88 code = request.POST.get('code')
91 invitation = Invitation.objects.get(code = code)
92 if invitation.is_consumed:
93 raise ValueError(_('Invitation is used'))
94 if reserved_email(invitation.username):
95 raise ValueError(_('Email: %s is reserved' % invitation.username))
98 def prepare_response(request, user, next='', renew=False):
99 """Return the unique username and the token
100 as 'X-Auth-User' and 'X-Auth-Token' headers,
101 or redirect to the URL provided in 'next'
102 with the 'user' and 'token' as parameters.
104 Reissue the token even if it has not yet
105 expired, if the 'renew' parameter is present
106 or user has not a valid token.
108 renew = renew or (not user.auth_token)
109 renew = renew or (user.auth_token_expires and user.auth_token_expires < datetime.datetime.now())
114 except ValidationError, e:
115 return HttpResponseBadRequest(e)
117 if FORCE_PROFILE_UPDATE and not user.is_verified and not user.is_superuser:
120 params = '?' + urlencode({'next': next})
121 next = reverse('astakos.im.views.edit_profile') + params
123 response = HttpResponse()
125 # authenticate before login
126 user = authenticate(email=user.email, auth_token=user.auth_token)
128 set_cookie(response, user)
129 request.session.set_expiry(user.auth_token_expires)
132 next = reverse('astakos.im.views.index')
134 response['Location'] = next
135 response.status_code = 302
138 def set_cookie(response, user):
139 expire_fmt = user.auth_token_expires.strftime('%a, %d-%b-%Y %H:%M:%S %Z')
140 cookie_value = quote(user.email + '|' + user.auth_token)
141 response.set_cookie(COOKIE_NAME, value=cookie_value,
142 expires=expire_fmt, path='/',
143 domain=COOKIE_DOMAIN, secure=COOKIE_SECURE)
145 class lazy_string(object):
146 def __init__(self, function, *args, **kwargs):
147 self.function=function
152 if not hasattr(self, 'str'):
153 self.str=self.function(*self.args, **self.kwargs)
156 def reverse_lazy(*args, **kwargs):
157 return lazy_string(reverse, *args, **kwargs)
159 def reserved_email(email):
160 return AstakosUser.objects.filter(email = email).count() != 0
162 def get_query(request):
163 return request.__getattribute__(request.method)