Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / cookie.py @ ab30f5f1

History | View | Annotate | Download (4.3 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.settings import (
42
    COOKIE_NAME, COOKIE_DOMAIN, COOKIE_SECURE, LOGGING_LEVEL, TRANSLATE_UUIDS)
43

    
44
import astakos.im.messages as astakos_messages
45

    
46
logger = logging.getLogger(__name__)
47

    
48

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

    
57
    @property
58
    def uuid(self):
59
        return getattr(self, 'uuid', '')
60

    
61
    @property
62
    def auth_token(self):
63
        return getattr(self, 'auth_token', '')
64

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

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

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

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

    
106
    def fix(self, response=None):
107
        self.response = response or self.response
108
        try:
109
            api_call = getattr(self.request, 'api_call', False)
110
            if api_call:
111
                return
112

    
113
            if self.user.is_authenticated():
114
                if not self.is_set or not self.is_valid:
115
                    self.__set()
116
            else:
117
                if self.is_set:
118
                    self.__delete()
119
        except AttributeError:
120
            pass