Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / util.py @ fc1e2f02

History | View | Annotate | Download (5.7 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

    
38
from urllib import quote
39

    
40
from datetime import tzinfo, timedelta
41
from django.http import HttpResponse, HttpResponseBadRequest, urlencode
42
from django.template import RequestContext
43
from django.utils.translation import ugettext as _
44
from django.contrib.auth import authenticate
45
from django.core.urlresolvers import reverse
46
from django.core.exceptions import ValidationError
47

    
48
from astakos.im.models import AstakosUser, Invitation
49
from astakos.im.settings import COOKIE_NAME, \
50
    COOKIE_DOMAIN, COOKIE_SECURE, FORCE_PROFILE_UPDATE, LOGGING_LEVEL
51
from astakos.im.functions import login
52

    
53
logger = logging.getLogger(__name__)
54

    
55
class UTC(tzinfo):
56
    def utcoffset(self, dt):
57
        return timedelta(0)
58
    
59
    def tzname(self, dt):
60
        return 'UTC'
61
    
62
    def dst(self, dt):
63
        return timedelta(0)
64

    
65
def isoformat(d):
66
    """Return an ISO8601 date string that includes a timezone."""
67
    
68
    return d.replace(tzinfo=UTC()).isoformat()
69

    
70
def epoch(datetime):
71
    return int(time.mktime(datetime.timetuple())*1000)
72

    
73
def get_context(request, extra_context=None, **kwargs):
74
    extra_context = extra_context or {}
75
    extra_context.update(kwargs)
76
    return RequestContext(request, extra_context)
77

    
78
def get_invitation(request):
79
    """
80
    Returns the invitation identified by the ``code``.
81
    
82
    Raises ValueError if the invitation is consumed or there is another account
83
    associated with this email.
84
    """
85
    code = request.GET.get('code')
86
    if request.method == 'POST':
87
        code = request.POST.get('code')
88
    if not code:
89
        return
90
    invitation = Invitation.objects.get(code = code)
91
    if invitation.is_consumed:
92
        raise ValueError(_('Invitation is used'))
93
    if reserved_email(invitation.username):
94
        raise ValueError(_('Email: %s is reserved' % invitation.username))
95
    return invitation
96

    
97
def prepare_response(request, user, next='', renew=False):
98
    """Return the unique username and the token
99
       as 'X-Auth-User' and 'X-Auth-Token' headers,
100
       or redirect to the URL provided in 'next'
101
       with the 'user' and 'token' as parameters.
102
       
103
       Reissue the token even if it has not yet
104
       expired, if the 'renew' parameter is present
105
       or user has not a valid token.
106
    """
107
    renew = renew or (not user.auth_token)
108
    renew = renew or (user.auth_token_expires and user.auth_token_expires < datetime.datetime.now())
109
    if renew:
110
        user.renew_token()
111
        try:
112
            user.save()
113
        except ValidationError, e:
114
            return HttpResponseBadRequest(e) 
115
    
116
    if FORCE_PROFILE_UPDATE and not user.is_verified and not user.is_superuser:
117
        params = ''
118
        if next:
119
            params = '?' + urlencode({'next': next})
120
        next = reverse('edit_profile') + params
121
    
122
    response = HttpResponse()
123
    
124
    # authenticate before login
125
    user = authenticate(email=user.email, auth_token=user.auth_token)
126
    login(request, user)
127
    set_cookie(response, user)
128
    request.session.set_expiry(user.auth_token_expires)
129
    
130
    if not next:
131
        next = reverse('index')
132
    
133
    response['Location'] = next
134
    response.status_code = 302
135
    return response
136

    
137
def set_cookie(response, user):
138
    expire_fmt = user.auth_token_expires.strftime('%a, %d-%b-%Y %H:%M:%S %Z')
139
    cookie_value = quote(user.email + '|' + user.auth_token)
140
    response.set_cookie(COOKIE_NAME, value=cookie_value,
141
                        expires=expire_fmt, path='/',
142
                        domain=COOKIE_DOMAIN, secure=COOKIE_SECURE)
143
    msg = 'Cookie [expiring %s] set for %s' % (user.auth_token_expires, user.email)
144
    logger.log(LOGGING_LEVEL, msg)
145

    
146
class lazy_string(object):
147
    def __init__(self, function, *args, **kwargs):
148
        self.function=function
149
        self.args=args
150
        self.kwargs=kwargs
151
        
152
    def __str__(self):
153
        if not hasattr(self, 'str'):
154
            self.str=self.function(*self.args, **self.kwargs)
155
        return self.str
156

    
157
def reverse_lazy(*args, **kwargs):
158
    return lazy_string(reverse, *args, **kwargs)
159

    
160
def reserved_email(email):
161
    return AstakosUser.objects.filter(email = email).count() != 0
162

    
163
def get_query(request):
164
    return request.__getattribute__(request.method)