Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / util.py @ 669cfe19

History | View | Annotate | Download (8.8 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 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.core.exceptions import ValidationError, ObjectDoesNotExist
46
from django.utils.translation import ugettext as _
47

    
48
from astakos.im.models import AstakosUser, Invitation
49
from astakos.im.settings import (
50
    COOKIE_DOMAIN, FORCE_PROFILE_UPDATE)
51
from astakos.im.functions import login
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(datetime):
76
    return int(time.mktime(datetime.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
def restrict_next(url, domain=None, allowed_schemes=()):
106
    """
107
    Return url if having the supplied ``domain`` (if present) or one of the ``allowed_schemes``.
108
    Otherwise return None.
109

110
    >>> print restrict_next('/im/feedback', '.okeanos.grnet.gr')
111
    /im/feedback
112
    >>> print restrict_next('pithos.okeanos.grnet.gr/im/feedback', '.okeanos.grnet.gr')
113
    //pithos.okeanos.grnet.gr/im/feedback
114
    >>> print restrict_next('https://pithos.okeanos.grnet.gr/im/feedback', '.okeanos.grnet.gr')
115
    https://pithos.okeanos.grnet.gr/im/feedback
116
    >>> print restrict_next('pithos://127.0.0,1', '.okeanos.grnet.gr')
117
    None
118
    >>> print restrict_next('pithos://127.0.0,1', '.okeanos.grnet.gr', allowed_schemes=('pithos'))
119
    pithos://127.0.0,1
120
    >>> print restrict_next('node1.example.com', '.okeanos.grnet.gr')
121
    None
122
    >>> print restrict_next('//node1.example.com', '.okeanos.grnet.gr')
123
    None
124
    >>> print restrict_next('https://node1.example.com', '.okeanos.grnet.gr')
125
    None
126
    >>> print restrict_next('https://node1.example.com')
127
    https://node1.example.com
128
    >>> print restrict_next('//node1.example.com')
129
    //node1.example.com
130
    >>> print restrict_next('node1.example.com')
131
    //node1.example.com
132
    """
133
    if not url:
134
        return
135
    parts = urlparse(url, scheme='http')
136
    if not parts.netloc and not parts.path.startswith('/'):
137
        # fix url if does not conforms RFC 1808
138
        url = '//%s' % url
139
        parts = urlparse(url, scheme='http')
140
    # TODO more scientific checks?
141
    if not parts.netloc:    # internal url
142
        return url
143
    elif not domain:
144
        return url
145
    elif parts.netloc.endswith(domain):
146
        return url
147
    elif parts.scheme in allowed_schemes:
148
        return url
149

    
150
def prepare_response(request, user, next='', renew=False):
151
    """Return the unique username and the token
152
       as 'X-Auth-User' and 'X-Auth-Token' headers,
153
       or redirect to the URL provided in 'next'
154
       with the 'user' and 'token' as parameters.
155

156
       Reissue the token even if it has not yet
157
       expired, if the 'renew' parameter is present
158
       or user has not a valid token.
159
    """
160
    renew = renew or (not user.auth_token)
161
    renew = renew or (user.auth_token_expires < datetime.datetime.now())
162
    if renew:
163
        user.renew_token(
164
            flush_sessions=True,
165
            current_key=request.session.session_key
166
        )
167
        try:
168
            user.save()
169
        except ValidationError, e:
170
            return HttpResponseBadRequest(e)
171

    
172
    next = restrict_next(next, domain=COOKIE_DOMAIN)
173

    
174
    if FORCE_PROFILE_UPDATE and not user.is_verified and not user.is_superuser:
175
        params = ''
176
        if next:
177
            params = '?' + urlencode({'next': next})
178
        next = reverse('edit_profile') + params
179

    
180
    response = HttpResponse()
181

    
182
    # authenticate before login
183
    user = authenticate(email=user.email, auth_token=user.auth_token)
184
    login(request, user)
185
    request.session.set_expiry(user.auth_token_expires)
186

    
187
    if not next:
188
        next = reverse('astakos.im.views.index')
189

    
190
    response['Location'] = next
191
    response.status_code = 302
192
    return response
193

    
194
class lazy_string(object):
195
    def __init__(self, function, *args, **kwargs):
196
        self.function = function
197
        self.args = args
198
        self.kwargs = kwargs
199

    
200
    def __str__(self):
201
        if not hasattr(self, 'str'):
202
            self.str = self.function(*self.args, **self.kwargs)
203
        return self.str
204

    
205

    
206
def reverse_lazy(*args, **kwargs):
207
    return lazy_string(reverse, *args, **kwargs)
208

    
209

    
210
def reserved_email(email):
211
    return AstakosUser.objects.user_exists(email)
212

    
213

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

    
220

    
221
def model_to_dict(obj, exclude=['AutoField', 'ForeignKey', 'OneToOneField'],
222
                  include_empty=True):
223
    '''
224
        serialize model object to dict with related objects
225

226
        author: Vadym Zakovinko <vp@zakovinko.com>
227
        date: January 31, 2011
228
        http://djangosnippets.org/snippets/2342/
229
    '''
230
    tree = {}
231
    for field_name in obj._meta.get_all_field_names():
232
        try:
233
            field = getattr(obj, field_name)
234
        except (ObjectDoesNotExist, AttributeError):
235
            continue
236

    
237
        if field.__class__.__name__ in ['RelatedManager', 'ManyRelatedManager']:
238
            if field.model.__name__ in exclude:
239
                continue
240

    
241
            if field.__class__.__name__ == 'ManyRelatedManager':
242
                exclude.append(obj.__class__.__name__)
243
            subtree = []
244
            for related_obj in getattr(obj, field_name).all():
245
                value = model_to_dict(related_obj, exclude=exclude)
246
                if value or include_empty:
247
                    subtree.append(value)
248
            if subtree or include_empty:
249
                tree[field_name] = subtree
250
            continue
251

    
252
        field = obj._meta.get_field_by_name(field_name)[0]
253
        if field.__class__.__name__ in exclude:
254
            continue
255

    
256
        if field.__class__.__name__ == 'RelatedObject':
257
            exclude.append(field.model.__name__)
258
            tree[field_name] = model_to_dict(getattr(obj, field_name),
259
                                             exclude=exclude)
260
            continue
261

    
262
        value = getattr(obj, field_name)
263
        if field.__class__.__name__ == 'ForeignKey':
264
            value = unicode(value) if value is not None else value
265
        if value or include_empty:
266
            tree[field_name] = value
267

    
268
    return tree