1+ import json
2+ import logging
3+ import urllib .parse
4+
15from .user import User
26import base64
37
@@ -6,29 +10,52 @@ class AmplitudeCookie:
610 """This class provides utility functions for parsing and handling identity from Amplitude cookies."""
711
812 @staticmethod
9- def cookie_name (api_key : str ) -> str :
13+ def cookie_name (api_key : str , new_format : bool = False ) -> str :
1014 """
1115 Get the cookie name that Amplitude sets for the provided
1216 Parameters:
1317 api_key (str): The Amplitude API Key
18+ new_format (bool): True if cookie is in Browser SDK 2.0 format
1419
1520 Returns:
1621 The cookie name that Amplitude sets for the provided Amplitude API Key
1722 """
1823 if not api_key :
1924 raise ValueError ("Invalid Amplitude API Key" )
25+
26+ if new_format :
27+ if len (api_key ) < 10 :
28+ raise ValueError ("Invalid Amplitude API Key" )
29+ return f"AMP_{ api_key [0 :10 ]} "
30+
31+ if len (api_key ) < 6 :
32+ raise ValueError ("Invalid Amplitude API Key" )
2033 return f"amp_{ api_key [0 :6 ]} "
2134
2235 @staticmethod
23- def parse (amplitude_cookie : str ) -> User :
36+ def parse (amplitude_cookie : str , new_format : bool = False ) -> User :
2437 """
2538 Parse a cookie string and returns user
2639 Parameters:
2740 amplitude_cookie (str): A string from the amplitude cookie
41+ new_format: True if cookie is in Browser SDK 2.0 format
2842
2943 Returns:
3044 Experiment User context containing a device_id and user_id (if available)
3145 """
46+
47+ if new_format :
48+ decoding = base64 .b64decode (amplitude_cookie ).decode ("utf-8" )
49+ try :
50+ user_session = json .loads (urllib .parse .unquote_plus (decoding ))
51+ if "userId" not in user_session :
52+ return User (user_id = None , device_id = user_session ["deviceId" ])
53+ return User (user_id = user_session ["userId" ], device_id = user_session ["deviceId" ])
54+ except Exception as e :
55+ logger = logging .getLogger ("Amplitude" )
56+ logger .error ("Error parsing the Amplitude cookie: " + str (e ))
57+ return User ()
58+
3259 values = amplitude_cookie .split ('.' )
3360 user_id = None
3461 if values [1 ]:
@@ -39,13 +66,24 @@ def parse(amplitude_cookie: str) -> User:
3966 return User (user_id = user_id , device_id = values [0 ])
4067
4168 @staticmethod
42- def generate (device_id : str ) -> str :
69+ def generate (device_id : str , new_format : bool = False ) -> str :
4370 """
4471 Generates a cookie string to set for the Amplitude Javascript SDK
4572 Parameters:
4673 device_id (str): A device id to set
74+ new_format: True if cookie is in Browser SDK 2.0 format
4775
4876 Returns:
4977 A cookie string to set for the Amplitude Javascript SDK to read
5078 """
51- return f"{ device_id } .........."
79+ if not new_format :
80+ return f"{ device_id } .........."
81+
82+ user_session_hash = {
83+ "deviceId" : device_id
84+ }
85+ json_data = json .dumps (user_session_hash )
86+ encoded_json = urllib .parse .quote (json_data )
87+ base64_encoded = base64 .b64encode (bytearray (encoded_json , "utf-8" )).decode ("utf-8" )
88+
89+ return base64_encoded
0 commit comments