root / astakos / im / util.py @ e015e9e6
History | View | Annotate | Download (5.9 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 logging |
35 |
import datetime |
36 |
|
37 |
from urllib import quote |
38 |
from urlparse import urlsplit, urlunsplit |
39 |
from functools import wraps |
40 |
|
41 |
from datetime import tzinfo, timedelta |
42 |
from django.http import HttpResponse, urlencode |
43 |
from django.template import RequestContext |
44 |
from django.contrib.sites.models import Site |
45 |
from django.utils.translation import ugettext as _ |
46 |
from django.contrib.auth import login, authenticate |
47 |
from django.core.urlresolvers import reverse |
48 |
|
49 |
from astakos.im.models import AstakosUser, Invitation |
50 |
from astakos.im.settings import INVITATIONS_PER_LEVEL, COOKIE_NAME, COOKIE_DOMAIN, FORCE_PROFILE_UPDATE |
51 |
|
52 |
logger = logging.getLogger(__name__) |
53 |
|
54 |
class UTC(tzinfo): |
55 |
def utcoffset(self, dt): |
56 |
return timedelta(0) |
57 |
|
58 |
def tzname(self, dt): |
59 |
return 'UTC' |
60 |
|
61 |
def dst(self, dt): |
62 |
return timedelta(0) |
63 |
|
64 |
def isoformat(d): |
65 |
"""Return an ISO8601 date string that includes a timezone."""
|
66 |
|
67 |
return d.replace(tzinfo=UTC()).isoformat()
|
68 |
|
69 |
def get_or_create_user(email, realname='', first_name='', last_name='', affiliation='', level=0, provider='local', password=''): |
70 |
"""Find or register a user into the internal database
|
71 |
and issue a token for subsequent requests.
|
72 |
"""
|
73 |
user, created = AstakosUser.objects.get_or_create(email=email, |
74 |
defaults={ |
75 |
'password':password,
|
76 |
'affiliation':affiliation,
|
77 |
'level':level,
|
78 |
'invitations':INVITATIONS_PER_LEVEL[level],
|
79 |
'provider':provider,
|
80 |
'realname':realname,
|
81 |
'first_name':first_name,
|
82 |
'last_name':last_name
|
83 |
}) |
84 |
if created:
|
85 |
user.renew_token() |
86 |
user.save() |
87 |
logger.info('Created user %s', user)
|
88 |
|
89 |
return user
|
90 |
|
91 |
def get_context(request, extra_context={}, **kwargs): |
92 |
if not extra_context: |
93 |
extra_context = {} |
94 |
extra_context.update(kwargs) |
95 |
return RequestContext(request, extra_context)
|
96 |
|
97 |
def get_current_site(request, use_https=False): |
98 |
"""
|
99 |
returns the current site name and full domain (including prorocol)
|
100 |
"""
|
101 |
protocol = use_https and 'https' or 'http' |
102 |
site = Site.objects.get_current() |
103 |
return site.name, '%s://%s' % (protocol, site.domain) |
104 |
|
105 |
def get_invitation(request): |
106 |
"""
|
107 |
Returns the invitation identified by the ``code``.
|
108 |
|
109 |
Raises Invitation.DoesNotExist and Exception if the invitation is consumed
|
110 |
"""
|
111 |
code = request.GET.get('code')
|
112 |
if request.method == 'POST': |
113 |
code = request.POST.get('code')
|
114 |
if not code: |
115 |
if 'invitation_code' in request.session: |
116 |
code = request.session.pop('invitation_code')
|
117 |
if not code: |
118 |
return
|
119 |
invitation = Invitation.objects.get(code = code) |
120 |
if invitation.is_consumed:
|
121 |
raise ValueError(_('Invitation is used')) |
122 |
try:
|
123 |
AstakosUser.objects.get(email = invitation.username) |
124 |
raise ValueError(_('Email: %s is reserved' % invitation.username)) |
125 |
except AstakosUser.DoesNotExist:
|
126 |
pass
|
127 |
return invitation
|
128 |
|
129 |
def prepare_response(request, user, next='', renew=False): |
130 |
"""Return the unique username and the token
|
131 |
as 'X-Auth-User' and 'X-Auth-Token' headers,
|
132 |
or redirect to the URL provided in 'next'
|
133 |
with the 'user' and 'token' as parameters.
|
134 |
|
135 |
Reissue the token even if it has not yet
|
136 |
expired, if the 'renew' parameter is present
|
137 |
or user has not a valid token.
|
138 |
"""
|
139 |
|
140 |
renew = renew or (not user.auth_token) |
141 |
renew = renew or (user.auth_token_expires and user.auth_token_expires < datetime.datetime.now()) |
142 |
if renew:
|
143 |
user.renew_token() |
144 |
user.save() |
145 |
|
146 |
if FORCE_PROFILE_UPDATE and not user.is_verified and not user.is_superuser: |
147 |
params = ''
|
148 |
if next: |
149 |
params = '?' + urlencode({'next': next}) |
150 |
next = reverse('astakos.im.views.edit_profile') + params
|
151 |
|
152 |
response = HttpResponse() |
153 |
|
154 |
# authenticate before login
|
155 |
user = authenticate(email=user.email, auth_token=user.auth_token) |
156 |
login(request, user) |
157 |
# set cookie
|
158 |
expire_fmt = user.auth_token_expires.strftime('%a, %d-%b-%Y %H:%M:%S %Z')
|
159 |
cookie_value = quote(user.email + '|' + user.auth_token)
|
160 |
response.set_cookie(COOKIE_NAME, value=cookie_value, |
161 |
expires=expire_fmt, path='/',
|
162 |
domain = COOKIE_DOMAIN) |
163 |
|
164 |
if not next: |
165 |
next = reverse('astakos.im.views.index')
|
166 |
|
167 |
response['Location'] = next |
168 |
response.status_code = 302
|
169 |
return response
|