xref: /aosp_15_r20/external/autotest/autotest_lib/tko/unique_cookie.py (revision 9c5db1993ded3edbeafc8092d69fe5de2ee02df7)
1# Lint as: python2, python3
2from __future__ import division
3from __future__ import print_function
4import os, random
5
6
7def unique_id(cookie_key):
8    """
9    Find out if remote caller has cookie set on the key.
10    If not, set cookie on client side: evaluate this key by a random string.
11    ( unique user identifier )
12    In both scenarios return value of the cookie, be it old or newly set one
13    """
14    uid = ''
15    ## try to retrieve uid from Cookie
16    if 'HTTP_COOKIE' in os.environ:
17        ## parse os.environ['HTTP_COOKIE']
18        cookies = os.environ['HTTP_COOKIE'].split(';')
19        key = '%s=' % cookie_key
20        uid_cookies = [c for c in cookies if c.strip().startswith(key)]
21
22        if uid_cookies:
23            assert(len(uid_cookies) == 1)
24            uid_cookie = uid_cookies[0]
25            uid = uid_cookie.replace(key, '')
26
27    if not uid:
28        uid = str(random.random())[2:16] # random string of 14 digits
29        set_cookie_statement = 'Set-Cookie:%s=%s;' % (cookie_key, uid)
30        set_cookie_statement += 'expires=Thu, 26-Dec-2013 22:03:25 GMT;'
31        print(set_cookie_statement)
32
33    return uid
34