Ticket #3285: middleware.py

File middleware.py, 1.3 KB (added by Marty Alchin <gulopine@…>, 18 years ago)

The only file necessary to make it work

Line 
1import re
2try:
3 from hashlib import md5 as hash
4except ImportError:
5 from md5 import new as hash
6
7from django.conf import settings
8
9regex = re.compile(r'([0-9a-f]+):(.*)$')
10
11class SignedCookiesMiddleware(object):
12
13 def process_request(self, request):
14 for (key, signed_value) in request.COOKIES.items():
15 try:
16 (signature, value) = regex.match(signed_value).groups()
17 assert signature == self.get_digest(key, value)
18 request.COOKIES[key] = value
19 except:
20 del request.COOKIES[key]
21
22 def process_response(self, request, response):
23 for (key, morsel) in response.cookies.items():
24 if morsel['expires'] == 0 and morsel['max-age'] == 0:
25 continue
26 digest = self.get_digest(key, morsel.value)
27 response.set_cookie(key, '%s:%s' % (digest, morsel.value),
28 max_age=morsel['max-age'],
29 expires=morsel['expires'],
30 path=morsel['path'],
31 domain=morsel['domain'],
32 secure=morsel['secure']
33 )
34 return response
35
36 def get_digest(self, key, value):
37 string = ':'.join([settings.SECRET_KEY, key, value])
38 return hash(string).hexdigest()
Back to Top