Skip to content

Commit

Permalink
Update AmplitudeCookie util to support new cookie format (#33)
Browse files Browse the repository at this point in the history
Co-authored-by: Tim Yiu <[email protected]>
  • Loading branch information
tyiuhc and Tim Yiu authored Oct 23, 2023
1 parent 838a9e1 commit 09af25d
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 6 deletions.
49 changes: 45 additions & 4 deletions packages/node/src/cookie.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { ConsoleLogger } from 'src/util/logger';

import { ExperimentUser } from './types/user';

/**
Expand All @@ -7,10 +9,18 @@ import { ExperimentUser } from './types/user';
export class AmplitudeCookie {
/**
* @param amplitudeApiKey The Amplitude API Key
* @param newFormat True if the cookie is in the Browser SDK 2.0 format
* @returns The cookie name that Amplitude sets for the provided
* Amplitude API Key
*/
public static cookieName(amplitudeApiKey: string): string {
public static cookieName(amplitudeApiKey: string, newFormat = false): string {
if (newFormat) {
if (amplitudeApiKey?.length < 10) {
throw Error('Invalid Amplitude API Key');
} else {
return 'AMP_' + amplitudeApiKey.substring(0, 10);
}
}
if (amplitudeApiKey?.length < 6) {
throw Error('Invalid Amplitude API Key');
}
Expand All @@ -19,10 +29,28 @@ export class AmplitudeCookie {

/**
* @param amplitudeCookie A string from the amplitude cookie
* @param newFormat True if the cookie is in the Browser SDK 2.0 format
* @returns a ExperimentUser context containing a device_id and user_id
* (if available)
*/
public static parse(amplitudeCookie: string): ExperimentUser {
public static parse(
amplitudeCookie: string,
newFormat = false,
): ExperimentUser {
if (newFormat) {
const decoding = Buffer.from(amplitudeCookie, 'base64').toString('utf-8');
try {
const userSession = JSON.parse(decodeURIComponent(decoding));
return {
device_id: userSession.deviceId,
user_id: userSession.userId,
};
} catch (e) {
const logger = new ConsoleLogger(true);
logger.error(`Error parsing the Amplitude cookie: ${e.message}`);
return {};
}
}
const values = amplitudeCookie.split('.');
let user_id = undefined;
if (values[1]) {
Expand All @@ -41,9 +69,22 @@ export class AmplitudeCookie {
/**
* Generates a cookie string to set for the Amplitude Javascript SDK
* @param deviceId A device id to set
* @param newFormat True if the cookie is in the Browser SDK 2.0 format
* @returns A cookie string to set for the Amplitude Javascript SDK to read
*/
public static generate(deviceId: string): string {
return deviceId + '..........';
public static generate(deviceId: string, newFormat = false): string {
if (!newFormat) {
return deviceId + '..........';
}

const userSessionHash = {
deviceId: deviceId,
};

const json_data = JSON.stringify(userSessionHash);
const encoded_json = encodeURIComponent(json_data);
const base64Encoded = Buffer.from(encoded_json).toString('base64');

return base64Encoded;
}
}
18 changes: 16 additions & 2 deletions packages/node/test/cookie.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import { AmplitudeCookie } from 'src/cookie';

const userAndDeviceNewCookie =
'JTdCJTIydXNlcklkJTIyJTNBJTIydGVzdCU0MGFtcGxpdHVkZS5jb20lMjIlMkMlMjJkZXZpY2VJZCUyMiUzQSUyMmRldmljZUlkJTIyJTdE';
const deviceNewCookie = 'JTdCJTIyZGV2aWNlSWQlMjIlM0ElMjJkZXZpY2VJZCUyMiU3RA==';

test('AmplitudeCookie.cookieName', () => {
expect(() => {
AmplitudeCookie.cookieName('');
}).toThrowError();
expect(AmplitudeCookie.cookieName('1234567')).toEqual('amp_123456');
expect(AmplitudeCookie.cookieName('1234567890', true)).toEqual(
'AMP_1234567890',
);
});

test('AmplitudeCookie.parse', () => {
Expand All @@ -13,7 +20,10 @@ test('AmplitudeCookie.parse', () => {
).toEqual({
device_id: 'deviceId',
});

expect(AmplitudeCookie.parse(deviceNewCookie, true)).toEqual({
device_id: 'deviceId',
});
expect(AmplitudeCookie.parse('invalidcookie', true)).toEqual({});
expect(
AmplitudeCookie.parse(
'deviceId.dGVzdEBhbXBsaXR1ZGUuY29t..1f1gkeib1.1f1gkeib1.dv.1ir.20q',
Expand All @@ -22,7 +32,10 @@ test('AmplitudeCookie.parse', () => {
device_id: 'deviceId',
user_id: '[email protected]',
});

expect(AmplitudeCookie.parse(userAndDeviceNewCookie, true)).toEqual({
device_id: 'deviceId',
user_id: '[email protected]',
});
expect(
AmplitudeCookie.parse('deviceId.Y8O3Pg==..1f1gkeib1.1f1gkeib1.dv.1ir.20q'),
).toEqual({
Expand All @@ -33,4 +46,5 @@ test('AmplitudeCookie.parse', () => {

test('AmplitudeCookie.generate', () => {
expect(AmplitudeCookie.generate('deviceId')).toEqual('deviceId..........');
expect(AmplitudeCookie.generate('deviceId', true)).toEqual(deviceNewCookie);
});

0 comments on commit 09af25d

Please sign in to comment.