Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / cookie.py @ 8fb8d0cf

History | View | Annotate | Download (4.2 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

    
36
from urllib import quote, unquote
37

    
38
from django.contrib.auth.models import AnonymousUser
39
from django.utils.translation import ugettext as _
40

    
41
from astakos.im import settings
42
import astakos.im.messages as astakos_messages
43

    
44
logger = logging.getLogger(__name__)
45

    
46

    
47
class CookieHandler():
48
    def __init__(self, request, response=None):
49
        cookies = getattr(request, 'COOKIES', {})
50
        cookie = unquote(cookies.get(settings.COOKIE_NAME, ''))
51
        self.uuid, sep, self.auth_token = cookie.partition('|')
52
        self.request = request
53
        self.response = response
54

    
55
    @property
56
    def uuid(self):
57
        return getattr(self, 'uuid', '')
58

    
59
    @property
60
    def auth_token(self):
61
        return getattr(self, 'auth_token', '')
62

    
63
    @property
64
    def is_set(self):
65
        no_token = not self.auth_token
66
        return not no_token
67

    
68
    @property
69
    def is_valid(self):
70
        cookie_attribute = ('uuid' if not settings.TRANSLATE_UUIDS
71
                            else 'username')
72
        return (self.uuid == getattr(self.user, cookie_attribute, '') and
73
                self.auth_token == getattr(self.user, 'auth_token', ''))
74

    
75
    @property
76
    def user(self):
77
        return getattr(self.request, 'user', AnonymousUser())
78

    
79
    def __set(self):
80
        if not self.response:
81
            raise ValueError(_(astakos_messages.NO_RESPONSE))
82
        user = self.user
83
        expire_fmt = user.auth_token_expires.strftime(
84
            '%a, %d-%b-%Y %H:%M:%S %Z')
85
        if settings.TRANSLATE_UUIDS:
86
            cookie_value = quote(user.username + '|' + user.auth_token)
87
        else:
88
            cookie_value = quote(user.uuid + '|' + user.auth_token)
89
        self.response.set_cookie(
90
            settings.COOKIE_NAME, value=cookie_value, expires=expire_fmt,
91
            path='/',
92
            domain=settings.COOKIE_DOMAIN, secure=settings.COOKIE_SECURE
93
        )
94
        msg = str(('Cookie [expiring %(auth_token_expires)s]',
95
                   'set for %(uuid)s')) % user.__dict__
96
        logger._log(settings.LOGGING_LEVEL, msg, [])
97

    
98
    def __delete(self):
99
        if not self.response:
100
            raise ValueError(_(astakos_messages.NO_RESPONSE))
101
        self.response.delete_cookie(
102
            settings.COOKIE_NAME, path='/', domain=settings.COOKIE_DOMAIN)
103
        msg = 'Cookie deleted for %(uuid)s' % self.__dict__
104
        logger._log(settings.LOGGING_LEVEL, msg, [])
105

    
106
    def fix(self, response=None):
107
        self.response = response or self.response
108
        try:
109
            if self.user.is_authenticated():
110
                if not self.is_set or not self.is_valid:
111
                    self.__set()
112
            else:
113
                if self.is_set:
114
                    self.__delete()
115
        except AttributeError:
116
            pass