Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / util.py @ 27e51b28

History | View | Annotate | Download (11.1 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 prepare_response(request, user, next='', renew=False):
180
    """Return the unique username and the token
181
       as 'X-Auth-User' and 'X-Auth-Token' headers,
182
       or redirect to the URL provided in 'next'
183
       with the 'user' and 'token' as parameters.
184

185
       Reissue the token even if it has not yet
186
       expired, if the 'renew' parameter is present
187
       or user has not a valid token.
188
    """
189
    renew = renew or (not user.auth_token)
190
    renew = renew or user.token_expired()
191
    if renew:
192
        user.renew_token(
193
            flush_sessions=True,
194
            current_key=request.session.session_key
195
        )
196
        try:
197
            user.save()
198
        except ValidationError, e:
199
            return HttpResponseBadRequest(e)
200

    
201
    next = restrict_next(next, domain=settings.COOKIE_DOMAIN)
202

    
203
    if settings.FORCE_PROFILE_UPDATE and \
204
            not user.is_verified and not user.is_superuser:
205
        params = ''
206
        if next:
207
            params = '?' + urlencode({'next': next})
208
        next = reverse('edit_profile') + params
209

    
210
    response = HttpResponse()
211

    
212
    # authenticate before login
213
    user = authenticate(email=user.email, auth_token=user.auth_token)
214
    login(request, user)
215
    request.session.set_expiry(user.auth_token_expires)
216

    
217
    if not next:
218
        next = settings.LOGIN_SUCCESS_URL
219

    
220
    response['Location'] = next
221
    response.status_code = 302
222
    return response
223

    
224

    
225
class lazy_string(object):
226
    def __init__(self, function, *args, **kwargs):
227
        self.function = function
228
        self.args = args
229
        self.kwargs = kwargs
230

    
231
    def __str__(self):
232
        if not hasattr(self, 'str'):
233
            self.str = self.function(*self.args, **self.kwargs)
234
        return self.str
235

    
236

    
237
def reverse_lazy(*args, **kwargs):
238
    return lazy_string(reverse, *args, **kwargs)
239

    
240

    
241
def reserved_email(email):
242
    return AstakosUser.objects.user_exists(email)
243

    
244

    
245
def reserved_verified_email(email):
246
    return AstakosUser.objects.verified_user_exists(email)
247

    
248

    
249
def get_query(request):
250
    try:
251
        return request.__getattribute__(request.method)
252
    except AttributeError:
253
        return {}
254

    
255

    
256
def get_properties(obj):
257
    def get_class_attr(_class, attr):
258
        try:
259
            return getattr(_class, attr)
260
        except AttributeError:
261
            return
262

    
263
    return (i for i in vars(obj.__class__)
264
            if isinstance(get_class_attr(obj.__class__, i), property))
265

    
266

    
267
def model_to_dict(obj, exclude=None, include_empty=True):
268
    '''
269
        serialize model object to dict with related objects
270

271
        author: Vadym Zakovinko <vp@zakovinko.com>
272
        date: January 31, 2011
273
        http://djangosnippets.org/snippets/2342/
274
    '''
275

    
276
    if exclude is None:
277
        exclude = ['AutoField', 'ForeignKey', 'OneToOneField']
278
    tree = {}
279
    for field_name in obj._meta.get_all_field_names():
280
        try:
281
            field = getattr(obj, field_name)
282
        except (ObjectDoesNotExist, AttributeError):
283
            continue
284

    
285
        if field.__class__.__name__ in ['RelatedManager',
286
                                        'ManyRelatedManager']:
287
            if field.model.__name__ in exclude:
288
                continue
289

    
290
            if field.__class__.__name__ == 'ManyRelatedManager':
291
                exclude.append(obj.__class__.__name__)
292
            subtree = []
293
            for related_obj in getattr(obj, field_name).all():
294
                value = model_to_dict(related_obj, exclude=exclude)
295
                if value or include_empty:
296
                    subtree.append(value)
297
            if subtree or include_empty:
298
                tree[field_name] = subtree
299
            continue
300

    
301
        field = obj._meta.get_field_by_name(field_name)[0]
302
        if field.__class__.__name__ in exclude:
303
            continue
304

    
305
        if field.__class__.__name__ == 'RelatedObject':
306
            exclude.append(field.model.__name__)
307
            tree[field_name] = model_to_dict(getattr(obj, field_name),
308
                                             exclude=exclude)
309
            continue
310

    
311
        value = getattr(obj, field_name)
312
        if field.__class__.__name__ == 'ForeignKey':
313
            value = unicode(value) if value is not None else value
314
        if value or include_empty:
315
            tree[field_name] = value
316
    properties = list(get_properties(obj))
317
    for p in properties:
318
        tree[p] = getattr(obj, p)
319
    tree['str_repr'] = obj.__str__()
320

    
321
    return tree
322

    
323

    
324
def login_url(request):
325
    attrs = {}
326
    for attr in ['login', 'key', 'code']:
327
        val = request.REQUEST.get(attr, None)
328
        if val:
329
            attrs[attr] = val
330
    return "%s?%s" % (reverse('login'), urllib.urlencode(attrs))
331

    
332

    
333
def redirect_back(request, default='index'):
334
    """
335
    Redirect back to referer if safe and possible.
336
    """
337
    referer = request.META.get('HTTP_REFERER')
338

    
339
    safedomain = settings.BASE_URL.replace("https://", "").replace(
340
        "http://", "")
341
    safe = restrict_next(referer, safedomain)
342
    # avoid redirect loop
343
    loops = referer == request.get_full_path()
344
    if referer and safe and not loops:
345
        return redirect(referer)
346
    return redirect(reverse(default))