Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / util.py @ 8fb8d0cf

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 datetime
36
import time
37
import urllib
38

    
39
from urlparse import urlparse
40
from datetime import tzinfo, timedelta
41

    
42
from django.http import HttpResponse, HttpResponseBadRequest, urlencode, \
43
    HttpResponseRedirect
44
from django.template import RequestContext
45
from django.contrib.auth import authenticate
46
from django.core.urlresolvers import reverse
47
from django.shortcuts import redirect
48
from django.core.exceptions import ValidationError, ObjectDoesNotExist
49
from django.utils.translation import ugettext as _
50

    
51
from astakos.im.models import AstakosUser, Invitation
52
from astakos.im.functions import login
53
from astakos.im import settings
54

    
55
import astakos.im.messages as astakos_messages
56

    
57
logger = logging.getLogger(__name__)
58

    
59

    
60
class UTC(tzinfo):
61
    def utcoffset(self, dt):
62
        return timedelta(0)
63

    
64
    def tzname(self, dt):
65
        return 'UTC'
66

    
67
    def dst(self, dt):
68
        return timedelta(0)
69

    
70

    
71
def isoformat(d):
72
    """Return an ISO8601 date string that includes a timezone."""
73

    
74
    return d.replace(tzinfo=UTC()).isoformat()
75

    
76

    
77
def epoch(dt):
78
    return int(time.mktime(dt.timetuple()) * 1000)
79

    
80

    
81
def get_context(request, extra_context=None, **kwargs):
82
    extra_context = extra_context or {}
83
    extra_context.update(kwargs)
84
    return RequestContext(request, extra_context)
85

    
86

    
87
def get_invitation(request):
88
    """
89
    Returns the invitation identified by the ``code``.
90

91
    Raises ValueError if the invitation is consumed or there is another account
92
    associated with this email.
93
    """
94
    code = request.GET.get('code')
95
    if request.method == 'POST':
96
        code = request.POST.get('code')
97
    if not code:
98
        return
99
    invitation = Invitation.objects.get(code=code)
100
    if invitation.is_consumed:
101
        raise ValueError(_(astakos_messages.INVITATION_CONSUMED_ERR))
102
    if reserved_email(invitation.username):
103
        email = invitation.username
104
        raise ValueError(_(astakos_messages.EMAIL_RESERVED) % locals())
105
    return invitation
106

    
107

    
108
def restrict_next(url, domain=None, allowed_schemes=()):
109
    """
110
    Utility method to validate that provided url is safe to be used as the
111
    redirect location of an http redirect response. The method parses the
112
    provided url and identifies if it conforms CORS against provided domain
113
    AND url scheme matches any of the schemes in `allowed_schemes` parameter.
114
    If verirication succeeds sanitized safe url is returned. Consider using
115
    the method's result in the response location header and not the originally
116
    provided url. If verification fails the method returns None.
117

118
    >>> print restrict_next('/im/feedback', '.okeanos.grnet.gr')
119
    /im/feedback
120
    >>> print restrict_next('pithos.okeanos.grnet.gr/im/feedback',
121
    ...                     '.okeanos.grnet.gr')
122
    //pithos.okeanos.grnet.gr/im/feedback
123
    >>> print restrict_next('https://pithos.okeanos.grnet.gr/im/feedback',
124
    ...                     '.okeanos.grnet.gr')
125
    https://pithos.okeanos.grnet.gr/im/feedback
126
    >>> print restrict_next('pithos://127.0.0.1', '.okeanos.grnet.gr')
127
    None
128
    >>> print restrict_next('pithos://127.0.0.1', '.okeanos.grnet.gr',
129
    ...                     allowed_schemes=('pithos'))
130
    None
131
    >>> print restrict_next('pithos://127.0.0.1', '127.0.0.1',
132
    ...                     allowed_schemes=('pithos'))
133
    pithos://127.0.0.1
134
    >>> print restrict_next('node1.example.com', '.okeanos.grnet.gr')
135
    None
136
    >>> print restrict_next('//node1.example.com', '.okeanos.grnet.gr')
137
    None
138
    >>> print restrict_next('https://node1.example.com', '.okeanos.grnet.gr')
139
    None
140
    >>> print restrict_next('https://node1.example.com')
141
    https://node1.example.com
142
    >>> print restrict_next('//node1.example.com')
143
    //node1.example.com
144
    >>> print restrict_next('node1.example.com')
145
    //node1.example.com
146
    >>> print restrict_next('node1.example.com', allowed_schemes=('pithos',))
147
    None
148
    >>> print restrict_next('pithos://localhost', 'localhost',
149
    ...                     allowed_schemes=('pithos',))
150
    pithos://localhost
151
    """
152
    if not url:
153
        return None
154

    
155
    parts = urlparse(url, scheme='http')
156
    if not parts.netloc and not parts.path.startswith('/'):
157
        # fix url if does not conforms RFC 1808
158
        url = '//%s' % url
159
        parts = urlparse(url, scheme='http')
160

    
161
    if not domain and not allowed_schemes:
162
        return url
163

    
164
    # domain validation
165
    if domain:
166
        if not parts.netloc:
167
            return url
168
        if parts.netloc.endswith(domain):
169
            return url
170
        else:
171
            return None
172

    
173
    # scheme validation
174
    if allowed_schemes:
175
        if parts.scheme in allowed_schemes:
176
            return url
177

    
178
    return None
179

    
180

    
181
def prepare_response(request, user, next='', renew=False):
182
    """Return the unique username and the token
183
       as 'X-Auth-User' and 'X-Auth-Token' headers,
184
       or redirect to the URL provided in 'next'
185
       with the 'user' and 'token' as parameters.
186

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

    
203
    next = restrict_next(next, domain=settings.COOKIE_DOMAIN)
204

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

    
212
    response = HttpResponse()
213

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

    
219
    if not next:
220
        next = settings.LOGIN_SUCCESS_URL
221

    
222
    response['Location'] = next
223
    response.status_code = 302
224
    return response
225

    
226

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

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

    
238

    
239
def reverse_lazy(*args, **kwargs):
240
    return lazy_string(reverse, *args, **kwargs)
241

    
242

    
243
def reserved_email(email):
244
    return AstakosUser.objects.user_exists(email)
245

    
246

    
247
def reserved_verified_email(email):
248
    return AstakosUser.objects.verified_user_exists(email)
249

    
250

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

    
257

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

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

    
268

    
269
def model_to_dict(obj, exclude=['AutoField', 'ForeignKey', 'OneToOneField'],
270
                  include_empty=True):
271
    '''
272
        serialize model object to dict with related objects
273

274
        author: Vadym Zakovinko <vp@zakovinko.com>
275
        date: January 31, 2011
276
        http://djangosnippets.org/snippets/2342/
277
    '''
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))