mbligh | 94f07a2 | 2008-05-21 17:10:57 +0000 | [diff] [blame] | 1 | import os, random |
| 2 | |
mbligh | d34763f | 2008-06-06 14:28:10 +0000 | [diff] [blame] | 3 | |
mbligh | 94f07a2 | 2008-05-21 17:10:57 +0000 | [diff] [blame] | 4 | def unique_id(cookie_key): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 5 | """ |
| 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)] |
mbligh | 94f07a2 | 2008-05-21 17:10:57 +0000 | [diff] [blame] | 18 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 19 | if uid_cookies: |
| 20 | assert(len(uid_cookies) == 1) |
| 21 | uid_cookie = uid_cookies[0] |
| 22 | uid = uid_cookie.replace(key, '') |
mbligh | 94f07a2 | 2008-05-21 17:10:57 +0000 | [diff] [blame] | 23 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 24 | 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 |
mbligh | 94f07a2 | 2008-05-21 17:10:57 +0000 | [diff] [blame] | 29 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 30 | return uid |