root / snf-astakos-app / astakos / im / util.py @ 6debe235
History | View | Annotate | Download (11.5 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 time |
36 |
import urllib |
37 |
|
38 |
from urlparse import urlparse |
39 |
from datetime import tzinfo, timedelta |
40 |
|
41 |
from django.http import HttpResponse, HttpResponseBadRequest, urlencode |
42 |
from django.template import RequestContext |
43 |
from django.contrib.auth import authenticate |
44 |
from django.core.urlresolvers import reverse |
45 |
from django.shortcuts import redirect |
46 |
from django.core.exceptions import ValidationError, ObjectDoesNotExist |
47 |
from django.utils.translation import ugettext as _ |
48 |
|
49 |
from astakos.im.models import AstakosUser, Invitation |
50 |
from astakos.im.functions import login |
51 |
from astakos.im import settings |
52 |
|
53 |
import astakos.im.messages as astakos_messages |
54 |
|
55 |
logger = logging.getLogger(__name__) |
56 |
|
57 |
|
58 |
class UTC(tzinfo): |
59 |
def utcoffset(self, dt): |
60 |
return timedelta(0) |
61 |
|
62 |
def tzname(self, dt): |
63 |
return 'UTC' |
64 |
|
65 |
def dst(self, dt): |
66 |
return timedelta(0) |
67 |
|
68 |
|
69 |
def isoformat(d): |
70 |
"""Return an ISO8601 date string that includes a timezone."""
|
71 |
|
72 |
return d.replace(tzinfo=UTC()).isoformat()
|
73 |
|
74 |
|
75 |
def epoch(dt): |
76 |
return int(time.mktime(dt.timetuple()) * 1000) |
77 |
|
78 |
|
79 |
def get_context(request, extra_context=None, **kwargs): |
80 |
extra_context = extra_context or {}
|
81 |
extra_context.update(kwargs) |
82 |
return RequestContext(request, extra_context)
|
83 |
|
84 |
|
85 |
def get_invitation(request): |
86 |
"""
|
87 |
Returns the invitation identified by the ``code``.
|
88 |
|
89 |
Raises ValueError if the invitation is consumed or there is another account
|
90 |
associated with this email.
|
91 |
"""
|
92 |
code = request.GET.get('code')
|
93 |
if request.method == 'POST': |
94 |
code = request.POST.get('code')
|
95 |
if not code: |
96 |
return
|
97 |
invitation = Invitation.objects.get(code=code) |
98 |
if invitation.is_consumed:
|
99 |
raise ValueError(_(astakos_messages.INVITATION_CONSUMED_ERR)) |
100 |
if reserved_email(invitation.username):
|
101 |
email = invitation.username |
102 |
raise ValueError(_(astakos_messages.EMAIL_RESERVED) % locals()) |
103 |
return invitation
|
104 |
|
105 |
|
106 |
def restrict_next(url, domain=None, allowed_schemes=()): |
107 |
"""
|
108 |
Utility method to validate that provided url is safe to be used as the
|
109 |
redirect location of an http redirect response. The method parses the
|
110 |
provided url and identifies if it conforms CORS against provided domain
|
111 |
AND url scheme matches any of the schemes in `allowed_schemes` parameter.
|
112 |
If verirication succeeds sanitized safe url is returned. Consider using
|
113 |
the method's result in the response location header and not the originally
|
114 |
provided url. If verification fails the method returns None.
|
115 |
|
116 |
>>> print restrict_next('/im/feedback', '.okeanos.grnet.gr')
|
117 |
/im/feedback
|
118 |
>>> print restrict_next('pithos.okeanos.grnet.gr/im/feedback',
|
119 |
... '.okeanos.grnet.gr')
|
120 |
//pithos.okeanos.grnet.gr/im/feedback
|
121 |
>>> print restrict_next('https://pithos.okeanos.grnet.gr/im/feedback',
|
122 |
... '.okeanos.grnet.gr')
|
123 |
https://pithos.okeanos.grnet.gr/im/feedback
|
124 |
>>> print restrict_next('pithos://127.0.0.1', '.okeanos.grnet.gr')
|
125 |
None
|
126 |
>>> print restrict_next('pithos://127.0.0.1', '.okeanos.grnet.gr',
|
127 |
... allowed_schemes=('pithos'))
|
128 |
None
|
129 |
>>> print restrict_next('pithos://127.0.0.1', '127.0.0.1',
|
130 |
... allowed_schemes=('pithos'))
|
131 |
pithos://127.0.0.1
|
132 |
>>> print restrict_next('node1.example.com', '.okeanos.grnet.gr')
|
133 |
None
|
134 |
>>> print restrict_next('//node1.example.com', '.okeanos.grnet.gr')
|
135 |
None
|
136 |
>>> print restrict_next('https://node1.example.com', '.okeanos.grnet.gr')
|
137 |
None
|
138 |
>>> print restrict_next('https://node1.example.com')
|
139 |
https://node1.example.com
|
140 |
>>> print restrict_next('//node1.example.com')
|
141 |
//node1.example.com
|
142 |
>>> print restrict_next('node1.example.com')
|
143 |
//node1.example.com
|
144 |
>>> print restrict_next('node1.example.com', allowed_schemes=('pithos',))
|
145 |
None
|
146 |
>>> print restrict_next('pithos://localhost', 'localhost',
|
147 |
... allowed_schemes=('pithos',))
|
148 |
pithos://localhost
|
149 |
"""
|
150 |
if not url: |
151 |
return None |
152 |
|
153 |
parts = urlparse(url, scheme='http')
|
154 |
if not parts.netloc and not parts.path.startswith('/'): |
155 |
# fix url if does not conforms RFC 1808
|
156 |
url = '//%s' % url
|
157 |
parts = urlparse(url, scheme='http')
|
158 |
|
159 |
if not domain and not allowed_schemes: |
160 |
return url
|
161 |
|
162 |
# domain validation
|
163 |
if domain:
|
164 |
if not parts.netloc: |
165 |
return url
|
166 |
if parts.netloc.endswith(domain):
|
167 |
return url
|
168 |
else:
|
169 |
return None |
170 |
|
171 |
# scheme validation
|
172 |
if allowed_schemes:
|
173 |
if parts.scheme in allowed_schemes: |
174 |
return url
|
175 |
|
176 |
return None |
177 |
|
178 |
|
179 |
def restrict_reverse(*args, **kwargs): |
180 |
"""
|
181 |
Like reverse, with an additional restrict_next call to the reverse result.
|
182 |
"""
|
183 |
domain = kwargs.pop('restrict_domain', settings.COOKIE_DOMAIN)
|
184 |
url = reverse(*args, **kwargs) |
185 |
return restrict_next(url, domain=domain)
|
186 |
|
187 |
|
188 |
def prepare_response(request, user, next='', renew=False): |
189 |
"""Return the unique username and the token
|
190 |
as 'X-Auth-User' and 'X-Auth-Token' headers,
|
191 |
or redirect to the URL provided in 'next'
|
192 |
with the 'user' and 'token' as parameters.
|
193 |
|
194 |
Reissue the token even if it has not yet
|
195 |
expired, if the 'renew' parameter is present
|
196 |
or user has not a valid token.
|
197 |
"""
|
198 |
renew = renew or (not user.auth_token) |
199 |
renew = renew or user.token_expired()
|
200 |
if renew:
|
201 |
user.renew_token( |
202 |
flush_sessions=True,
|
203 |
current_key=request.session.session_key |
204 |
) |
205 |
try:
|
206 |
user.save() |
207 |
except ValidationError, e:
|
208 |
return HttpResponseBadRequest(e)
|
209 |
|
210 |
next = restrict_next(next, domain=settings.COOKIE_DOMAIN)
|
211 |
|
212 |
if settings.FORCE_PROFILE_UPDATE and \ |
213 |
not user.is_verified and not user.is_superuser: |
214 |
params = ''
|
215 |
if next: |
216 |
params = '?' + urlencode({'next': next}) |
217 |
next = reverse('edit_profile') + params
|
218 |
|
219 |
response = HttpResponse() |
220 |
|
221 |
# authenticate before login
|
222 |
user = authenticate(email=user.email, auth_token=user.auth_token) |
223 |
login(request, user) |
224 |
request.session.set_expiry(user.auth_token_expires) |
225 |
|
226 |
if not next: |
227 |
next = settings.LOGIN_SUCCESS_URL |
228 |
|
229 |
response['Location'] = next |
230 |
response.status_code = 302
|
231 |
return response
|
232 |
|
233 |
|
234 |
class lazy_string(object): |
235 |
def __init__(self, function, *args, **kwargs): |
236 |
self.function = function
|
237 |
self.args = args
|
238 |
self.kwargs = kwargs
|
239 |
|
240 |
def __str__(self): |
241 |
if not hasattr(self, 'str'): |
242 |
self.str = self.function(*self.args, **self.kwargs) |
243 |
return self.str |
244 |
|
245 |
|
246 |
def reverse_lazy(*args, **kwargs): |
247 |
return lazy_string(reverse, *args, **kwargs)
|
248 |
|
249 |
|
250 |
def reserved_email(email): |
251 |
return AstakosUser.objects.user_exists(email)
|
252 |
|
253 |
|
254 |
def reserved_verified_email(email): |
255 |
return AstakosUser.objects.verified_user_exists(email)
|
256 |
|
257 |
|
258 |
def get_query(request): |
259 |
try:
|
260 |
return request.__getattribute__(request.method)
|
261 |
except AttributeError: |
262 |
return {}
|
263 |
|
264 |
|
265 |
def get_properties(obj): |
266 |
def get_class_attr(_class, attr): |
267 |
try:
|
268 |
return getattr(_class, attr) |
269 |
except AttributeError: |
270 |
return
|
271 |
|
272 |
return (i for i in vars(obj.__class__) |
273 |
if isinstance(get_class_attr(obj.__class__, i), property)) |
274 |
|
275 |
|
276 |
def model_to_dict(obj, exclude=None, include_empty=True): |
277 |
'''
|
278 |
serialize model object to dict with related objects
|
279 |
|
280 |
author: Vadym Zakovinko <vp@zakovinko.com>
|
281 |
date: January 31, 2011
|
282 |
http://djangosnippets.org/snippets/2342/
|
283 |
'''
|
284 |
|
285 |
if exclude is None: |
286 |
exclude = ['AutoField', 'ForeignKey', 'OneToOneField'] |
287 |
tree = {} |
288 |
for field_name in obj._meta.get_all_field_names(): |
289 |
try:
|
290 |
field = getattr(obj, field_name)
|
291 |
except (ObjectDoesNotExist, AttributeError): |
292 |
continue
|
293 |
|
294 |
if field.__class__.__name__ in ['RelatedManager', |
295 |
'ManyRelatedManager']:
|
296 |
if field.model.__name__ in exclude: |
297 |
continue
|
298 |
|
299 |
if field.__class__.__name__ == 'ManyRelatedManager': |
300 |
exclude.append(obj.__class__.__name__) |
301 |
subtree = [] |
302 |
for related_obj in getattr(obj, field_name).all(): |
303 |
value = model_to_dict(related_obj, exclude=exclude) |
304 |
if value or include_empty: |
305 |
subtree.append(value) |
306 |
if subtree or include_empty: |
307 |
tree[field_name] = subtree |
308 |
continue
|
309 |
|
310 |
field = obj._meta.get_field_by_name(field_name)[0]
|
311 |
if field.__class__.__name__ in exclude: |
312 |
continue
|
313 |
|
314 |
if field.__class__.__name__ == 'RelatedObject': |
315 |
exclude.append(field.model.__name__) |
316 |
tree[field_name] = model_to_dict(getattr(obj, field_name),
|
317 |
exclude=exclude) |
318 |
continue
|
319 |
|
320 |
value = getattr(obj, field_name)
|
321 |
if field.__class__.__name__ == 'ForeignKey': |
322 |
value = unicode(value) if value is not None else value |
323 |
if value or include_empty: |
324 |
tree[field_name] = value |
325 |
properties = list(get_properties(obj))
|
326 |
for p in properties: |
327 |
tree[p] = getattr(obj, p)
|
328 |
tree['str_repr'] = obj.__str__()
|
329 |
|
330 |
return tree
|
331 |
|
332 |
|
333 |
def login_url(request): |
334 |
attrs = {} |
335 |
for attr in ['login', 'key', 'code']: |
336 |
val = request.REQUEST.get(attr, None)
|
337 |
if val:
|
338 |
attrs[attr] = val |
339 |
return "%s?%s" % (reverse('login'), urllib.urlencode(attrs)) |
340 |
|
341 |
|
342 |
def redirect_back(request, default='index'): |
343 |
"""
|
344 |
Redirect back to referer if safe and possible.
|
345 |
"""
|
346 |
referer = request.META.get('HTTP_REFERER')
|
347 |
|
348 |
safedomain = settings.BASE_URL.replace("https://", "").replace( |
349 |
"http://", "") |
350 |
safe = restrict_next(referer, safedomain) |
351 |
# avoid redirect loop
|
352 |
loops = referer == request.get_full_path() |
353 |
if referer and safe and not loops: |
354 |
return redirect(referer)
|
355 |
return redirect(reverse(default))
|
356 |
|
357 |
|
358 |
def truncatename(v, max=18, append="..."): |
359 |
length = len(v)
|
360 |
if length > max: |
361 |
return v[:max] + append |
362 |
else:
|
363 |
return v
|