blob: 292d12ae86653f6991dd722c2968fb27952b1f53 [file] [log] [blame]
mbligh94f07a22008-05-21 17:10:57 +00001#!/usr/bin/env python
2
3import os, random
4
mblighd34763f2008-06-06 14:28:10 +00005
mbligh94f07a22008-05-21 17:10:57 +00006def unique_id(cookie_key):
jadmanski0afbb632008-06-06 21:10:57 +00007 """
8 Find out if remote caller has cookie set on the key.
9 If not, set cookie on client side: evaluate this key by a random string.
10 ( unique user identifier )
11 In both scenarios return value of the cookie, be it old or newly set one
12 """
13 uid = ''
14 ## try to retrieve uid from Cookie
15 if 'HTTP_COOKIE' in os.environ:
16 ## parse os.environ['HTTP_COOKIE']
17 cookies = os.environ['HTTP_COOKIE'].split(';')
18 key = '%s=' % cookie_key
19 uid_cookies = [c for c in cookies if c.strip().startswith(key)]
mbligh94f07a22008-05-21 17:10:57 +000020
jadmanski0afbb632008-06-06 21:10:57 +000021 if uid_cookies:
22 assert(len(uid_cookies) == 1)
23 uid_cookie = uid_cookies[0]
24 uid = uid_cookie.replace(key, '')
mbligh94f07a22008-05-21 17:10:57 +000025
jadmanski0afbb632008-06-06 21:10:57 +000026 if not uid:
27 uid = str(random.random())[2:16] # random string of 14 digits
28 set_cookie_statement = 'Set-Cookie:%s=%s;' % (cookie_key, uid)
29 set_cookie_statement += 'expires=Thu, 26-Dec-2013 22:03:25 GMT;'
30 print set_cookie_statement
mbligh94f07a22008-05-21 17:10:57 +000031
jadmanski0afbb632008-06-06 21:10:57 +000032 return uid