util.py 5.62 KB
Newer Older
Antony Chazapis's avatar
Antony Chazapis committed
1
# Copyright 2011-2012 GRNET S.A. All rights reserved.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
# 
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
# 
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
# 
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# 
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
34
import logging
35
36
37
38
39
import datetime

from urllib import quote
from urlparse import urlsplit, urlunsplit
from functools import wraps
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
40

41
from datetime import tzinfo, timedelta
42
from django.http import HttpResponse, urlencode
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
43
from django.template import RequestContext
44
from django.contrib.sites.models import Site
45
from django.utils.translation import ugettext as _
46
47
from django.contrib.auth import login, authenticate
from django.core.urlresolvers import reverse
48

49
from astakos.im.models import AstakosUser, Invitation
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
50
from astakos.im.settings import INVITATIONS_PER_LEVEL, COOKIE_NAME, COOKIE_DOMAIN, FORCE_PROFILE_UPDATE
51

52
53
logger = logging.getLogger(__name__)

54
55
56
57
58
59
60
61
62
63
64
65
66
67
class UTC(tzinfo):
   def utcoffset(self, dt):
       return timedelta(0)

   def tzname(self, dt):
       return 'UTC'

   def dst(self, dt):
       return timedelta(0)

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

   return d.replace(tzinfo=UTC()).isoformat()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
68

69
def get_or_create_user(email, realname='', first_name='', last_name='', affiliation='', level=0, provider='local', password=''):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
70
71
72
    """Find or register a user into the internal database
       and issue a token for subsequent requests.
    """
73
    user, created = AstakosUser.objects.get_or_create(email=email,
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
74
75
76
77
        defaults={
            'password':password,
            'affiliation':affiliation,
            'level':level,
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
78
            'invitations':INVITATIONS_PER_LEVEL[level],
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
79
80
81
82
83
84
85
86
            'provider':provider,
            'realname':realname,
            'first_name':first_name,
            'last_name':last_name
        })
    if created:
        user.renew_token()
        user.save()
87
        logger.info('Created user %s', user)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
88
89
90
91
92
93
94
95
    
    return user

def get_context(request, extra_context={}, **kwargs):
    if not extra_context:
        extra_context = {}
    extra_context.update(kwargs)
    return RequestContext(request, extra_context)
96

97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
def get_invitation(request):
    """
    Returns the invitation identified by the ``code``.
    
    Raises Invitation.DoesNotExist and Exception if the invitation is consumed
    """
    code = request.GET.get('code')
    if request.method == 'POST':
        code = request.POST.get('code')
    if not code:
        if 'invitation_code' in request.session:
            code = request.session.pop('invitation_code')
    if not code:
        return
    invitation = Invitation.objects.get(code = code)
    if invitation.is_consumed:
113
        raise ValueError(_('Invitation is used'))
114
115
116
117
118
    try:
        AstakosUser.objects.get(email = invitation.username)
        raise ValueError(_('Email: %s is reserved' % invitation.username))
    except AstakosUser.DoesNotExist:
        pass
119
120
    return invitation

root's avatar
root committed
121
def prepare_response(request, user, next='', renew=False):
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
    """Return the unique username and the token
       as 'X-Auth-User' and 'X-Auth-Token' headers,
       or redirect to the URL provided in 'next'
       with the 'user' and 'token' as parameters.
       
       Reissue the token even if it has not yet
       expired, if the 'renew' parameter is present
       or user has not a valid token.
    """
    
    renew = renew or (not user.auth_token)
    renew = renew or (user.auth_token_expires and user.auth_token_expires < datetime.datetime.now())
    if renew:
        user.renew_token()
        user.save()
    
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
138
    if FORCE_PROFILE_UPDATE and not user.is_verified and not user.is_superuser:
139
140
141
142
143
144
145
        params = ''
        if next:
            params = '?' + urlencode({'next': next})
        next = reverse('astakos.im.views.edit_profile') + params
    
    response = HttpResponse()
    
root's avatar
root committed
146
147
148
149
150
151
    # authenticate before login
    user = authenticate(email=user.email, auth_token=user.auth_token)
    login(request, user)
    # set cookie
    expire_fmt = user.auth_token_expires.strftime('%a, %d-%b-%Y %H:%M:%S %Z')
    cookie_value = quote(user.email + '|' + user.auth_token)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
152
    response.set_cookie(COOKIE_NAME, value=cookie_value,
root's avatar
root committed
153
                        expires=expire_fmt, path='/',
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
154
                        domain = COOKIE_DOMAIN)
155
156
157
158
159
160
    
    if not next:
        next = reverse('astakos.im.views.index')
    
    response['Location'] = next
    response.status_code = 302
root's avatar
root committed
161
    return response