blob: 112acdc05a95f6bb0feb0bfec54cb7d923257ce3 [file] [log] [blame]
mbligh94f07a22008-05-21 17:10:57 +00001import os, random
2
mblighd34763f2008-06-06 14:28:10 +00003
mbligh94f07a22008-05-21 17:10:57 +00004def unique_id(cookie_key):
jadmanski0afbb632008-06-06 21:10:57 +00005 """
6 Find out if remote caller has cookie set on the key.
7 If not, set cookie on client side: evaluate this key by a random string.
8 ( unique user identifier )
9 In both scenarios return value of the cookie, be it old or newly set one
10 """
11 uid = ''
12 ## try to retrieve uid from Cookie
13 if 'HTTP_COOKIE' in os.environ:
14 ## parse os.environ['HTTP_COOKIE']
15 cookies = os.environ['HTTP_COOKIE'].split(';')
16 key = '%s=' % cookie_key
17 uid_cookies = [c for c in cookies if c.strip().startswith(key)]
mbligh94f07a22008-05-21 17:10:57 +000018
jadmanski0afbb632008-06-06 21:10:57 +000019 if uid_cookies:
20 assert(len(uid_cookies) == 1)
21 uid_cookie = uid_cookies[0]
22 uid = uid_cookie.replace(key, '')
mbligh94f07a22008-05-21 17:10:57 +000023
jadmanski0afbb632008-06-06 21:10:57 +000024 if not uid:
25 uid = str(random.random())[2:16] # random string of 14 digits
26 set_cookie_statement = 'Set-Cookie:%s=%s;' % (cookie_key, uid)
27 set_cookie_statement += 'expires=Thu, 26-Dec-2013 22:03:25 GMT;'
28 print set_cookie_statement
mbligh94f07a22008-05-21 17:10:57 +000029
jadmanski0afbb632008-06-06 21:10:57 +000030 return uid