Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / util.py @ 217994f8

History | View | Annotate | Download (7.6 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
from urlparse import urlsplit, urlunsplit, urlparse
40

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

    
49
from astakos.im.models import AstakosUser, Invitation, ApprovalTerms
50
from astakos.im.settings import (
51
    INVITATIONS_PER_LEVEL, COOKIE_NAME, COOKIE_DOMAIN, COOKIE_SECURE,
52
    FORCE_PROFILE_UPDATE, LOGGING_LEVEL
53
)
54
from astakos.im.functions import login
55

    
56
logger = logging.getLogger(__name__)
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
def isoformat(d):
69
   """Return an ISO8601 date string that includes a timezone."""
70

    
71
   return d.replace(tzinfo=UTC()).isoformat()
72

    
73
def epoch(datetime):
74
    return int(time.mktime(datetime.timetuple())*1000)
75

    
76
def get_context(request, extra_context={}, **kwargs):
77
    if not extra_context:
78
        extra_context = {}
79
    extra_context.update(kwargs)
80
    return RequestContext(request, extra_context)
81

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

    
101
def restrict_next(url, domain=None, allowed_schemes=()):
102
    """
103
    Return url if having the supplied ``domain`` (if present) or one of the ``allowed_schemes``.
104
    Otherwise return None.
105
    
106
    >>> print restrict_next('/im/feedback', '.okeanos.grnet.gr')
107
    /im/feedback
108
    >>> print restrict_next('pithos.okeanos.grnet.gr/im/feedback', '.okeanos.grnet.gr')
109
    pithos.okeanos.grnet.gr/im/feedback
110
    >>> print restrict_next('https://pithos.okeanos.grnet.gr/im/feedback', '.okeanos.grnet.gr')
111
    https://pithos.okeanos.grnet.gr/im/feedback
112
    >>> print restrict_next('pithos://127.0.0,1', '.okeanos.grnet.gr')
113
    None
114
    >>> print restrict_next('pithos://127.0.0,1', '.okeanos.grnet.gr', allowed_schemes=('pithos'))
115
    pithos://127.0.0,1
116
    >>> print restrict_next('node1.example.com', '.okeanos.grnet.gr')
117
    None
118
    >>> print restrict_next('//node1.example.com', '.okeanos.grnet.gr')
119
    None
120
    >>> print restrict_next('https://node1.example.com', '.okeanos.grnet.gr')
121
    None
122
    >>> print restrict_next('https://node1.example.com')
123
    https://node1.example.com
124
    >>> print restrict_next('//node1.example.com')
125
    //node1.example.com
126
    >>> print restrict_next('node1.example.com')
127
    node1.example.com
128
    """
129
    if not url:
130
        return
131
    parts = urlparse(url, scheme='http')
132
    if not parts.netloc:
133
        # fix url if does not conforms RFC 1808
134
        url = '//%s' % url
135
        parts = urlparse(url, scheme='http')
136
    # TODO more scientific checks?
137
    if not parts.netloc:    # internal url
138
        return url
139
    elif not domain:
140
        return url
141
    elif parts.netloc.endswith(domain):
142
        return url
143
    elif parts.scheme in allowed_schemes:
144
        return url
145

    
146
def prepare_response(request, user, next='', renew=False):
147
    """Return the unique username and the token
148
       as 'X-Auth-User' and 'X-Auth-Token' headers,
149
       or redirect to the URL provided in 'next'
150
       with the 'user' and 'token' as parameters.
151
       
152
       Reissue the token even if it has not yet
153
       expired, if the 'renew' parameter is present
154
       or user has not a valid token.
155
    """
156
    renew = renew or (not user.auth_token)
157
    renew = renew or (user.auth_token_expires and user.auth_token_expires < datetime.datetime.now())
158
    if renew:
159
        user.renew_token()
160
        try:
161
            user.save()
162
        except ValidationError, e:
163
            return HttpResponseBadRequest(e) 
164
    
165
    next = restrict_next(next, domain=COOKIE_DOMAIN)
166
    
167
    if FORCE_PROFILE_UPDATE and not user.is_verified and not user.is_superuser:
168
        params = ''
169
        if next:
170
            params = '?' + urlencode({'next': next})
171
        next = reverse('astakos.im.views.edit_profile') + params
172
    
173
    response = HttpResponse()
174
    
175
    # authenticate before login
176
    user = authenticate(email=user.email, auth_token=user.auth_token)
177
    login(request, user)
178
    set_cookie(response, user)
179
    request.session.set_expiry(user.auth_token_expires)
180
    
181
    if not next:
182
        next = reverse('astakos.im.views.index')
183
    
184
    response['Location'] = next
185
    response.status_code = 302
186
    return response
187

    
188
def set_cookie(response, user):
189
    expire_fmt = user.auth_token_expires.strftime('%a, %d-%b-%Y %H:%M:%S %Z')
190
    cookie_value = quote(user.email + '|' + user.auth_token)
191
    response.set_cookie(COOKIE_NAME, value=cookie_value,
192
                        expires=expire_fmt, path='/',
193
                        domain=COOKIE_DOMAIN, secure=COOKIE_SECURE)
194
    msg = 'Cookie [expiring %s] set for %s' % (user.auth_token_expires, user.email)
195
    logger._log(LOGGING_LEVEL, msg, [])
196

    
197
class lazy_string(object):
198
    def __init__(self, function, *args, **kwargs):
199
        self.function=function
200
        self.args=args
201
        self.kwargs=kwargs
202
        
203
    def __str__(self):
204
        if not hasattr(self, 'str'):
205
            self.str=self.function(*self.args, **self.kwargs)
206
        return self.str
207

    
208
def reverse_lazy(*args, **kwargs):
209
    return lazy_string(reverse, *args, **kwargs)
210

    
211
def reserved_email(email):
212
    return AstakosUser.objects.filter(email = email).count() != 0
213

    
214
def get_query(request):
215
    try:
216
        return request.__getattribute__(request.method)
217
    except AttributeError:
218
        return {}