Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (7.2 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
from django.contrib.sessions.backends.base import SessionBase
49

    
50
from astakos.im.models import AstakosUser, Invitation, ApprovalTerms
51
from astakos.im.settings import (
52
    INVITATIONS_PER_LEVEL, COOKIE_DOMAIN, 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 and not parts.path.startswith('/'):
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
            flush_sessions=True,
161
            current_key=request.session.session_key
162
        )
163
        try:
164
            user.save()
165
        except ValidationError, e:
166
            return HttpResponseBadRequest(e) 
167
    
168
    next = restrict_next(next, domain=COOKIE_DOMAIN)
169
    
170
    if FORCE_PROFILE_UPDATE and not user.is_verified and not user.is_superuser:
171
        params = ''
172
        if next:
173
            params = '?' + urlencode({'next': next})
174
        next = reverse('astakos.im.views.edit_profile') + params
175
    
176
    response = HttpResponse()
177
    
178
    # authenticate before login
179
    user = authenticate(email=user.email, auth_token=user.auth_token)
180
    login(request, user)
181
    request.session.set_expiry(user.auth_token_expires)
182
    
183
    if not next:
184
        next = reverse('astakos.im.views.index')
185
        
186
    response['Location'] = next
187
    response.status_code = 302
188
    return response
189

    
190
class lazy_string(object):
191
    def __init__(self, function, *args, **kwargs):
192
        self.function=function
193
        self.args=args
194
        self.kwargs=kwargs
195
        
196
    def __str__(self):
197
        if not hasattr(self, 'str'):
198
            self.str=self.function(*self.args, **self.kwargs)
199
        return self.str
200

    
201
def reverse_lazy(*args, **kwargs):
202
    return lazy_string(reverse, *args, **kwargs)
203

    
204
def reserved_email(email):
205
    return AstakosUser.objects.filter(email = email).count() != 0
206

    
207
def get_query(request):
208
    try:
209
        return request.__getattribute__(request.method)
210
    except AttributeError:
211
        return {}