Statistics
| Branch: | Tag: | Revision:

root / astakos / im / target / util.py @ a196eb7e

History | View | Annotate | Download (3.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 datetime
35

    
36
from urlparse import urlsplit, urlunsplit
37
from urllib import quote
38
from functools import wraps
39

    
40
from django.http import HttpResponse
41
from django.utils.http import urlencode
42
from django.core.urlresolvers import reverse
43
from django.conf import settings
44
from django.contrib.auth import login, logout
45

    
46
def prepare_response(request, user, next='', renew=False, skip_login=False):
47
    """Return the unique username and the token
48
       as 'X-Auth-User' and 'X-Auth-Token' headers,
49
       or redirect to the URL provided in 'next'
50
       with the 'user' and 'token' as parameters.
51
       
52
       Reissue the token even if it has not yet
53
       expired, if the 'renew' parameter is present
54
       or user has not a valid token.
55
    """
56
    
57
    renew = renew or (not user.auth_token)
58
    renew = renew or (user.auth_token_expires and user.auth_token_expires < datetime.datetime.now())
59
    if renew:
60
        user.renew_token()
61
        user.save()
62
    
63
    if next:
64
        # TODO: Avoid redirect loops.
65
        parts = list(urlsplit(next))
66
        if not parts[1] or (parts[1] and request.get_host() != parts[1]):
67
            parts[3] = urlencode({'user': user.email, 'token': user.auth_token})
68
            next = urlunsplit(parts)
69
    
70
    if settings.FORCE_PROFILE_UPDATE and not user.is_verified and not user.is_superuser:
71
        params = ''
72
        if next:
73
            params = '?' + urlencode({'next': next})
74
        next = reverse('astakos.im.views.edit_profile') + params
75
    
76
    # user login
77
    if not skip_login:
78
        login(request, user)
79
    
80
    response = HttpResponse()
81
    
82
    # set cookie
83
    expire_fmt = user.auth_token_expires.strftime('%a, %d-%b-%Y %H:%M:%S %Z')        
84
    cookie_value = quote(user.email + '|' + user.auth_token)
85
    response.set_cookie(settings.COOKIE_NAME, value=cookie_value,
86
                        expires=expire_fmt, path='/',
87
                        domain = settings.COOKIE_DOMAIN)
88
    
89
    if not next:
90
        next = reverse('astakos.im.views.index')
91
    
92
    response['Location'] = next
93
    response.status_code = 302
94
    return response
95

    
96
def requires_anonymous(func):
97
    """
98
    Decorator checkes whether the request.user is an Anonymous and if not
99
    logouts the request.user.
100
    """
101
    @wraps(func)
102
    def wrapper(request, *args):
103
        if not request.user.is_anonymous():
104
            logout(request)
105
        return func(request, *args)
106
    return wrapper