Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / util.py @ 9a06d96f

History | View | Annotate | Download (7.5 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, ObjectDoesNotExist
47
from django.db.models.fields import Field
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

    
56
class UTC(tzinfo):
57
    def utcoffset(self, dt):
58
        return timedelta(0)
59

    
60
    def tzname(self, dt):
61
        return 'UTC'
62

    
63
    def dst(self, dt):
64
        return timedelta(0)
65

    
66

    
67
def isoformat(d):
68
    """Return an ISO8601 date string that includes a timezone."""
69

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

    
72

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

    
76

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

    
82

    
83
def get_invitation(request):
84
    """
85
    Returns the invitation identified by the ``code``.
86

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

    
102

    
103
def prepare_response(request, user, next='', renew=False):
104
    """Return the unique username and the token
105
       as 'X-Auth-User' and 'X-Auth-Token' headers,
106
       or redirect to the URL provided in 'next'
107
       with the 'user' and 'token' as parameters.
108

109
       Reissue the token even if it has not yet
110
       expired, if the 'renew' parameter is present
111
       or user has not a valid token.
112
    """
113
    renew = renew or (not user.auth_token)
114
    renew = renew or (user.auth_token_expires < datetime.datetime.now())
115
    if renew:
116
        user.renew_token()
117
        try:
118
            user.save()
119
        except ValidationError, e:
120
            return HttpResponseBadRequest(e)
121

    
122
    if FORCE_PROFILE_UPDATE and not user.is_verified and not user.is_superuser:
123
        params = ''
124
        if next:
125
            params = '?' + urlencode({'next': next})
126
        next = reverse('edit_profile') + params
127

    
128
    response = HttpResponse()
129

    
130
    # authenticate before login
131
    user = authenticate(email=user.email, auth_token=user.auth_token)
132
    login(request, user)
133
    set_cookie(response, user)
134
    request.session.set_expiry(user.auth_token_expires)
135

    
136
    if not next:
137
        next = reverse('index')
138

    
139
    response['Location'] = next
140
    response.status_code = 302
141
    return response
142

    
143

    
144
def set_cookie(response, user):
145
    expire_fmt = user.auth_token_expires.strftime('%a, %d-%b-%Y %H:%M:%S %Z')
146
    cookie_value = quote(user.email + '|' + user.auth_token)
147
    response.set_cookie(COOKIE_NAME, value=cookie_value,
148
                        expires=expire_fmt, path='/',
149
                        domain=COOKIE_DOMAIN, secure=COOKIE_SECURE)
150
    msg = 'Cookie [expiring %s] set for %s' % (
151
        user.auth_token_expires,
152
        user.email
153
    )
154
    logger.log(LOGGING_LEVEL, msg)
155

    
156

    
157
class lazy_string(object):
158
    def __init__(self, function, *args, **kwargs):
159
        self.function = function
160
        self.args = args
161
        self.kwargs = kwargs
162

    
163
    def __str__(self):
164
        if not hasattr(self, 'str'):
165
            self.str = self.function(*self.args, **self.kwargs)
166
        return self.str
167

    
168

    
169
def reverse_lazy(*args, **kwargs):
170
    return lazy_string(reverse, *args, **kwargs)
171

    
172

    
173
def reserved_email(email):
174
    return AstakosUser.objects.filter(email__iexact=email).count() != 0
175

    
176

    
177
def get_query(request):
178
    try:
179
        return request.__getattribute__(request.method)
180
    except AttributeError:
181
        return {}
182

    
183

    
184
def model_to_dict(obj, exclude=['AutoField', 'ForeignKey', 'OneToOneField'],
185
                  include_empty=True):
186
    '''
187
        serialize model object to dict with related objects
188

189
        author: Vadym Zakovinko <vp@zakovinko.com>
190
        date: January 31, 2011
191
        http://djangosnippets.org/snippets/2342/
192
    '''
193
    tree = {}
194
    for field_name in obj._meta.get_all_field_names():
195
        try:
196
            field = getattr(obj, field_name)
197
        except (ObjectDoesNotExist, AttributeError):
198
            continue
199

    
200
        if field.__class__.__name__ in ['RelatedManager', 'ManyRelatedManager']:
201
            if field.model.__name__ in exclude:
202
                continue
203

    
204
            if field.__class__.__name__ == 'ManyRelatedManager':
205
                exclude.append(obj.__class__.__name__)
206
            subtree = []
207
            for related_obj in getattr(obj, field_name).all():
208
                value = model_to_dict(related_obj, exclude=exclude)
209
                if value or include_empty:
210
                    subtree.append(value)
211
            if subtree or include_empty:
212
                tree[field_name] = subtree
213
            continue
214

    
215
        field = obj._meta.get_field_by_name(field_name)[0]
216
        if field.__class__.__name__ in exclude:
217
            continue
218

    
219
        if field.__class__.__name__ == 'RelatedObject':
220
            exclude.append(field.model.__name__)
221
            tree[field_name] = model_to_dict(getattr(obj, field_name),
222
                                             exclude=exclude)
223
            continue
224

    
225
        value = getattr(obj, field_name)
226
        if field.__class__.__name__ == 'ForeignKey':
227
            value = unicode(value) if value is not None else value
228
        if value or include_empty:
229
            tree[field_name] = value
230

    
231
    return tree