Statistics
| Branch: | Tag: | Revision:

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

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

    
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 django.utils.translation import ugettext as _
49

    
50
from astakos.im.models import AstakosUser, Invitation
51
from astakos.im.settings import COOKIE_NAME, \
52
    COOKIE_DOMAIN, COOKIE_SECURE, FORCE_PROFILE_UPDATE, LOGGING_LEVEL
53
from astakos.im.functions import login
54

    
55
import astakos.im.messages as astakos_messages
56

    
57
logger = logging.getLogger(__name__)
58

    
59

    
60
class UTC(tzinfo):
61
    def utcoffset(self, dt):
62
        return timedelta(0)
63

    
64
    def tzname(self, dt):
65
        return 'UTC'
66

    
67
    def dst(self, dt):
68
        return timedelta(0)
69

    
70

    
71
def isoformat(d):
72
    """Return an ISO8601 date string that includes a timezone."""
73

    
74
    return d.replace(tzinfo=UTC()).isoformat()
75

    
76

    
77
def epoch(datetime):
78
    return int(time.mktime(datetime.timetuple()) * 1000)
79

    
80

    
81
def get_context(request, extra_context=None, **kwargs):
82
    extra_context = extra_context or {}
83
    extra_context.update(kwargs)
84
    return RequestContext(request, extra_context)
85

    
86

    
87
def get_invitation(request):
88
    """
89
    Returns the invitation identified by the ``code``.
90

91
    Raises ValueError if the invitation is consumed or there is another account
92
    associated with this email.
93
    """
94
    code = request.GET.get('code')
95
    if request.method == 'POST':
96
        code = request.POST.get('code')
97
    if not code:
98
        return
99
    invitation = Invitation.objects.get(code=code)
100
    if invitation.is_consumed:
101
        raise ValueError(_(astakos_messages.INVITATION_CONSUMED_ERR))
102
    if reserved_email(invitation.username):
103
        email = invitation.username
104
        raise ValueError(_(astakos_messages.EMAIL_RESRVED) % locals()))
105
    return invitation
106

    
107

    
108
def prepare_response(request, user, next='', renew=False):
109
    """Return the unique username and the token
110
       as 'X-Auth-User' and 'X-Auth-Token' headers,
111
       or redirect to the URL provided in 'next'
112
       with the 'user' and 'token' as parameters.
113

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

    
127
    if FORCE_PROFILE_UPDATE and not user.is_verified and not user.is_superuser:
128
        params = ''
129
        if next:
130
            params = '?' + urlencode({'next': next})
131
        next = reverse('edit_profile') + params
132

    
133
    response = HttpResponse()
134

    
135
    # authenticate before login
136
    user = authenticate(email=user.email, auth_token=user.auth_token)
137
    login(request, user)
138
    set_cookie(response, user)
139
    request.session.set_expiry(user.auth_token_expires)
140

    
141
    if not next:
142
        next = reverse('index')
143

    
144
    response['Location'] = next
145
    response.status_code = 302
146
    return response
147

    
148

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

    
161

    
162
class lazy_string(object):
163
    def __init__(self, function, *args, **kwargs):
164
        self.function = function
165
        self.args = args
166
        self.kwargs = kwargs
167

    
168
    def __str__(self):
169
        if not hasattr(self, 'str'):
170
            self.str = self.function(*self.args, **self.kwargs)
171
        return self.str
172

    
173

    
174
def reverse_lazy(*args, **kwargs):
175
    return lazy_string(reverse, *args, **kwargs)
176

    
177

    
178
def reserved_email(email):
179
    return AstakosUser.objects.filter(email__iexact=email).count() != 0
180

    
181

    
182
def get_query(request):
183
    try:
184
        return request.__getattribute__(request.method)
185
    except AttributeError:
186
        return {}
187

    
188

    
189
def model_to_dict(obj, exclude=['AutoField', 'ForeignKey', 'OneToOneField'],
190
                  include_empty=True):
191
    '''
192
        serialize model object to dict with related objects
193

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

    
205
        if field.__class__.__name__ in ['RelatedManager', 'ManyRelatedManager']:
206
            if field.model.__name__ in exclude:
207
                continue
208

    
209
            if field.__class__.__name__ == 'ManyRelatedManager':
210
                exclude.append(obj.__class__.__name__)
211
            subtree = []
212
            for related_obj in getattr(obj, field_name).all():
213
                value = model_to_dict(related_obj, exclude=exclude)
214
                if value or include_empty:
215
                    subtree.append(value)
216
            if subtree or include_empty:
217
                tree[field_name] = subtree
218
            continue
219

    
220
        field = obj._meta.get_field_by_name(field_name)[0]
221
        if field.__class__.__name__ in exclude:
222
            continue
223

    
224
        if field.__class__.__name__ == 'RelatedObject':
225
            exclude.append(field.model.__name__)
226
            tree[field_name] = model_to_dict(getattr(obj, field_name),
227
                                             exclude=exclude)
228
            continue
229

    
230
        value = getattr(obj, field_name)
231
        if field.__class__.__name__ == 'ForeignKey':
232
            value = unicode(value) if value is not None else value
233
        if value or include_empty:
234
            tree[field_name] = value
235

    
236
    return tree