Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / util.py @ 9a94c0f1

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 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
def reserved_email(email):
235
    return AstakosUser.objects.user_exists(email)
236

    
237

    
238
def reserved_verified_email(email):
239
    return AstakosUser.objects.verified_user_exists(email)
240

    
241

    
242
def get_query(request):
243
    try:
244
        return request.__getattribute__(request.method)
245
    except AttributeError:
246
        return {}
247

    
248

    
249
def get_properties(obj):
250
    def get_class_attr(_class, attr):
251
        try:
252
            return getattr(_class, attr)
253
        except AttributeError:
254
            return
255

    
256
    return (i for i in vars(obj.__class__)
257
            if isinstance(get_class_attr(obj.__class__, i), property))
258

    
259

    
260
def model_to_dict(obj, exclude=None, include_empty=True):
261
    '''
262
        serialize model object to dict with related objects
263

264
        author: Vadym Zakovinko <vp@zakovinko.com>
265
        date: January 31, 2011
266
        http://djangosnippets.org/snippets/2342/
267
    '''
268

    
269
    if exclude is None:
270
        exclude = ['AutoField', 'ForeignKey', 'OneToOneField']
271
    tree = {}
272
    for field_name in obj._meta.get_all_field_names():
273
        try:
274
            field = getattr(obj, field_name)
275
        except (ObjectDoesNotExist, AttributeError):
276
            continue
277

    
278
        if field.__class__.__name__ in ['RelatedManager',
279
                                        'ManyRelatedManager']:
280
            if field.model.__name__ in exclude:
281
                continue
282

    
283
            if field.__class__.__name__ == 'ManyRelatedManager':
284
                exclude.append(obj.__class__.__name__)
285
            subtree = []
286
            for related_obj in getattr(obj, field_name).all():
287
                value = model_to_dict(related_obj, exclude=exclude)
288
                if value or include_empty:
289
                    subtree.append(value)
290
            if subtree or include_empty:
291
                tree[field_name] = subtree
292
            continue
293

    
294
        field = obj._meta.get_field_by_name(field_name)[0]
295
        if field.__class__.__name__ in exclude:
296
            continue
297

    
298
        if field.__class__.__name__ == 'RelatedObject':
299
            exclude.append(field.model.__name__)
300
            tree[field_name] = model_to_dict(getattr(obj, field_name),
301
                                             exclude=exclude)
302
            continue
303

    
304
        value = getattr(obj, field_name)
305
        if field.__class__.__name__ == 'ForeignKey':
306
            value = unicode(value) if value is not None else value
307
        if value or include_empty:
308
            tree[field_name] = value
309
    properties = list(get_properties(obj))
310
    for p in properties:
311
        tree[p] = getattr(obj, p)
312
    tree['str_repr'] = obj.__str__()
313

    
314
    return tree
315

    
316

    
317
def login_url(request):
318
    attrs = {}
319
    for attr in ['login', 'key', 'code']:
320
        val = request.REQUEST.get(attr, None)
321
        if val:
322
            attrs[attr] = val
323
    return "%s?%s" % (reverse('login'), urllib.urlencode(attrs))
324

    
325

    
326
def redirect_back(request, default='index'):
327
    """
328
    Redirect back to referer if safe and possible.
329
    """
330
    referer = request.META.get('HTTP_REFERER')
331

    
332
    safedomain = settings.BASE_URL.replace("https://", "").replace(
333
        "http://", "")
334
    safe = restrict_next(referer, safedomain)
335
    # avoid redirect loop
336
    loops = referer == request.get_full_path()
337
    if referer and safe and not loops:
338
        return redirect(referer)
339
    return redirect(reverse(default))
340

    
341

    
342
def truncatename(v, max=18, append="..."):
343
    length = len(v)
344
    if length > max:
345
        return v[:max] + append
346
    else:
347
        return v