mbligh | 94f07a2 | 2008-05-21 17:10:57 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | |
| 3 | import os, random |
| 4 | |
mbligh | d34763f | 2008-06-06 14:28:10 +0000 | [diff] [blame] | 5 | |
mbligh | 94f07a2 | 2008-05-21 17:10:57 +0000 | [diff] [blame] | 6 | def unique_id(cookie_key): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame^] | 7 | """ |
| 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)] |
mbligh | 94f07a2 | 2008-05-21 17:10:57 +0000 | [diff] [blame] | 20 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame^] | 21 | if uid_cookies: |
| 22 | assert(len(uid_cookies) == 1) |
| 23 | uid_cookie = uid_cookies[0] |
| 24 | uid = uid_cookie.replace(key, '') |
mbligh | 94f07a2 | 2008-05-21 17:10:57 +0000 | [diff] [blame] | 25 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame^] | 26 | 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 |
mbligh | 94f07a2 | 2008-05-21 17:10:57 +0000 | [diff] [blame] | 31 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame^] | 32 | return uid |