Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / util.py @ 0a7a4104

History | View | Annotate | Download (9.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
import urllib
38

    
39
from urlparse import urlparse
40
from datetime import tzinfo, timedelta
41

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

    
49
from astakos.im.models import AstakosUser, Invitation
50
from astakos.im.functions import login
51
from astakos.im import settings
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=settings.COOKIE_DOMAIN)
173

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

    
181
    response = HttpResponse()
182

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

    
188
    if not next:
189
        next = settings.LOGIN_SUCCESS_URL
190

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

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

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

    
206

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

    
210

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

    
214

    
215
def reserved_verified_email(email):
216
    return AstakosUser.objects.verified_user_exists(email)
217

    
218

    
219
def get_query(request):
220
    try:
221
        return request.__getattribute__(request.method)
222
    except AttributeError:
223
        return {}
224

    
225
def get_properties(obj):
226
    def get_class_attr(_class, attr):
227
        try:
228
            return getattr(_class, attr)
229
        except AttributeError:
230
            return
231

    
232
    return (i for i in vars(obj.__class__) \
233
        if isinstance(get_class_attr(obj.__class__, i), property))
234

    
235
def model_to_dict(obj, exclude=['AutoField', 'ForeignKey', 'OneToOneField'],
236
                  include_empty=True):
237
    '''
238
        serialize model object to dict with related objects
239

240
        author: Vadym Zakovinko <vp@zakovinko.com>
241
        date: January 31, 2011
242
        http://djangosnippets.org/snippets/2342/
243
    '''
244
    tree = {}
245
    for field_name in obj._meta.get_all_field_names():
246
        try:
247
            field = getattr(obj, field_name)
248
        except (ObjectDoesNotExist, AttributeError):
249
            continue
250

    
251
        if field.__class__.__name__ in ['RelatedManager', 'ManyRelatedManager']:
252
            if field.model.__name__ in exclude:
253
                continue
254

    
255
            if field.__class__.__name__ == 'ManyRelatedManager':
256
                exclude.append(obj.__class__.__name__)
257
            subtree = []
258
            for related_obj in getattr(obj, field_name).all():
259
                value = model_to_dict(related_obj, exclude=exclude)
260
                if value or include_empty:
261
                    subtree.append(value)
262
            if subtree or include_empty:
263
                tree[field_name] = subtree
264
            continue
265

    
266
        field = obj._meta.get_field_by_name(field_name)[0]
267
        if field.__class__.__name__ in exclude:
268
            continue
269

    
270
        if field.__class__.__name__ == 'RelatedObject':
271
            exclude.append(field.model.__name__)
272
            tree[field_name] = model_to_dict(getattr(obj, field_name),
273
                                             exclude=exclude)
274
            continue
275

    
276
        value = getattr(obj, field_name)
277
        if field.__class__.__name__ == 'ForeignKey':
278
            value = unicode(value) if value is not None else value
279
        if value or include_empty:
280
            tree[field_name] = value
281
    properties = list(get_properties(obj))
282
    for p in properties:
283
       tree[p] = getattr(obj, p)
284
    tree['str_repr'] = obj.__str__()
285

    
286
    return tree
287

    
288
def login_url(request):
289
    attrs = {}
290
    for attr in ['login', 'key', 'code']:
291
        val = request.REQUEST.get(attr, None)
292
        if val:
293
            attrs[attr] = val
294
    return "%s?%s" % (reverse('login'), urllib.urlencode(attrs))