-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathidentity-utils.ts
More file actions
404 lines (356 loc) · 12.9 KB
/
Copy pathidentity-utils.ts
File metadata and controls
404 lines (356 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
import Constants, { ONE_DAY_IN_SECONDS, MILLIS_IN_ONE_SEC } from './constants';
import { Dictionary, Environment, parseNumber, isObject, generateHash, generateUniqueId, isEmpty, isFunction } from './utils';
import { BaseVault } from './vault';
import Types from './types';
import {
IdentityApiData,
UserIdentities,
IdentityCallback,
} from '@mparticle/web-sdk';
import { IdentityAPIMethod, IIdentityRequest } from './identity.interfaces';
import {
IdentityResultBody,
IIdentityResponse,
IMParticleUser,
} from './identity-user-interfaces';
import { IStore } from './store';
import type { IMParticleWebSDKInstance } from './mp-instance';
import {
IIdentitySearchKnownIdentities,
IIdentitySearchRequestBody,
IdentitySearchCallback,
sendSearchRequest,
} from './identity/search';
const { Identify, Modify, Login, Logout } = Constants.IdentityMethods;
const { HTTPCodes, Messages } = Constants;
export const CACHE_HEADER = 'x-mp-max-age' as const;
export type IdentityCache = BaseVault<Dictionary<ICachedIdentityCall>>;
// https://go.mparticle.com/work/SQDSDKS-6675
export type IParseCachedIdentityResponse = (
cachedIdentity: IIdentityResponse,
mpid: string,
callback: IdentityCallback,
identityApiData: IdentityApiData,
identityMethod: string,
knownIdentities: IKnownIdentities,
fromCachedIdentity: boolean
) => void;
export interface IKnownIdentities extends UserIdentities {
device_application_stamp?: string;
}
export interface ICachedIdentityCall {
// https://go.mparticle.com/work/SQDSDKS-6672
responseText: string;
status: number;
expireTimestamp: number;
}
export const cacheOrClearIdCache = (
method: string,
knownIdentities: IKnownIdentities,
idCache: BaseVault<Dictionary<ICachedIdentityCall>>,
identityResponse: IIdentityResponse,
parsingCachedResponse: boolean
): void => {
// when parsing a response that has already been cached, simply return instead of attempting another cache
if (parsingCachedResponse) {
return;
}
// default the expire timestamp to one day in milliseconds unless a header comes back
const expireTimestamp = getExpireTimestamp(identityResponse?.cacheMaxAge);
switch (method) {
case Login:
case Identify:
cacheIdentityRequest(
method,
knownIdentities,
expireTimestamp,
idCache,
identityResponse
);
break;
case Modify:
case Logout:
idCache.purge();
break;
}
};
export const cacheIdentityRequest = (
method: IdentityAPIMethod,
identities: IKnownIdentities,
expireTimestamp: number,
idCache: IdentityCache,
identityResponse: IIdentityResponse
): void => {
const { responseText, status } = identityResponse;
const cache: Dictionary<ICachedIdentityCall> =
idCache.retrieve() || ({} as Dictionary<ICachedIdentityCall>);
const cacheKey = concatenateIdentities(method, identities);
const hashedKey = generateHash(cacheKey);
const { mpid, is_logged_in } = responseText;
const cachedResponseBody = {
mpid,
is_logged_in,
};
cache[hashedKey] = {
responseText: JSON.stringify(cachedResponseBody),
status,
expireTimestamp,
};
idCache.store(cache);
};
// We need to ensure that identities are concatenated in a deterministic way, so
// we sort the identities based on their enum.
// we create an array, set the user identity at the index of the user identity type
export const concatenateIdentities = (
method: IdentityAPIMethod,
userIdentities: IKnownIdentities
): string => {
const DEVICE_APPLICATION_STAMP = 'device_application_stamp';
// set DAS first since it is not an official identity type
let cacheKey: string = `${method}:${DEVICE_APPLICATION_STAMP}=${userIdentities.device_application_stamp};`;
const idLength: number = Object.keys(userIdentities).length;
let concatenatedIdentities: string = '';
if (idLength) {
let userIDArray: Array<string> = new Array();
// create an array where each index is equal to the user identity type
for (let key in userIdentities) {
if (key === DEVICE_APPLICATION_STAMP) {
continue;
} else {
userIDArray[Types.IdentityType.getIdentityType(key)] =
userIdentities[key];
}
}
concatenatedIdentities = userIDArray.reduce(
(prevValue: string, currentValue: string, index: number) => {
const idName: string =
Types.IdentityType.getIdentityName(index);
return `${prevValue}${idName}=${currentValue};`;
},
cacheKey
);
}
return concatenatedIdentities;
};
export const hasValidCachedIdentity = (
method: IdentityAPIMethod,
proposedUserIdentities: IKnownIdentities,
idCache?: IdentityCache
): boolean => {
// There is an edge case where multiple identity calls are taking place
// before identify fires, so there may not be a cache. See what happens when
// the ? in idCache is removed to the following test
// "queued events contain login mpid instead of identify mpid when calling
// login immediately after mParticle initializes"
const cache = idCache?.retrieve();
// if there is no cache, then there is no valid cached identity
if (!cache) {
return false;
}
const cacheKey: string = concatenateIdentities(
method,
proposedUserIdentities
);
const hashedKey = generateHash(cacheKey);
// if cache doesn't have the cacheKey, there is no valid cached identity
if (!cache.hasOwnProperty(hashedKey)) {
return false;
}
// If there is a valid cache key, compare the expireTimestamp to the current time.
// If the current time is greater than the expireTimestamp, it is not a valid
// cached identity.
const expireTimestamp = cache[hashedKey].expireTimestamp;
if (expireTimestamp < new Date().getTime()) {
return false;
} else {
return true;
}
};
export const getCachedIdentity = (
method: IdentityAPIMethod,
proposedUserIdentities: IKnownIdentities,
idCache: IdentityCache
): IIdentityResponse | null => {
const cacheKey: string = concatenateIdentities(
method,
proposedUserIdentities
);
const hashedKey = generateHash(cacheKey);
const cache = idCache.retrieve();
const cachedIdentity = cache ? cache[hashedKey] : null;
return {
responseText: parseIdentityResponse(cachedIdentity.responseText),
expireTimestamp: cachedIdentity.expireTimestamp,
status: cachedIdentity.status,
};
};
// https://go.mparticle.com/work/SQDSDKS-6079
export const createKnownIdentities = (
identityApiData: IdentityApiData,
deviceId: string
): IKnownIdentities => {
const identitiesResult: IKnownIdentities = {};
if (isObject(identityApiData?.userIdentities)) {
for (let identity in identityApiData.userIdentities) {
identitiesResult[identity] =
identityApiData.userIdentities[identity];
}
}
identitiesResult.device_application_stamp = deviceId;
return identitiesResult;
};
export const removeExpiredIdentityCacheDates = (
idCache: BaseVault<Dictionary<ICachedIdentityCall>>
) => {
const cache: Dictionary<ICachedIdentityCall> =
idCache.retrieve() || ({} as Dictionary<ICachedIdentityCall>);
const currentTime: number = new Date().getTime();
// Iterate over the cache and remove any key/value pairs that are expired
for (let key in cache) {
if (cache[key].expireTimestamp < currentTime) {
delete cache[key];
}
}
idCache.store(cache);
};
export const tryCacheIdentity = (
knownIdentities: IKnownIdentities,
idCache: IdentityCache,
parseIdentityResponse: IParseCachedIdentityResponse,
mpid: string,
callback: IdentityCallback,
identityApiData: IdentityApiData,
identityMethod: IdentityAPIMethod
): boolean => {
// https://go.mparticle.com/work/SQDSDKS-6095
const shouldReturnCachedIdentity = hasValidCachedIdentity(
identityMethod,
knownIdentities,
idCache
);
// If Identity is cached, then immediately parse the identity response
if (shouldReturnCachedIdentity) {
const cachedIdentity = getCachedIdentity(
identityMethod,
knownIdentities,
idCache
);
parseIdentityResponse(
cachedIdentity,
mpid,
callback,
identityApiData,
identityMethod,
knownIdentities,
true
);
return true;
}
return false;
};
const getExpireTimestamp = (maxAge: number = ONE_DAY_IN_SECONDS): number =>
new Date().getTime() + maxAge * MILLIS_IN_ONE_SEC;
const parseIdentityResponse = (responseText: string): IdentityResultBody =>
responseText ? JSON.parse(responseText) : ({} as IdentityResultBody);
export const hasIdentityRequestChanged = (
currentUser: IMParticleUser,
newIdentityRequest: IdentityApiData
): boolean => {
if (!currentUser || !newIdentityRequest?.userIdentities) {
return false;
}
const currentUserIdentities =
currentUser.getUserIdentities().userIdentities;
const newIdentities = newIdentityRequest.userIdentities;
return (
JSON.stringify(currentUserIdentities) !== JSON.stringify(newIdentities)
);
};
/**
* Checks if deviceId or other user identifiers (like email) were explicitly provided
* by the partner via config.deviceId or config.identifyRequest.userIdentities.
* When noFunctional is true, then cookies are blocked, so the partner must explicitly
* pass deviceId or other identifiers to prevent new users from being created on each page load.
*
* @param store - The SDK store (provides SDKConfig.deviceId and SDKConfig.identifyRequest.userIdentities)
* @returns true if deviceId or other identifiers were explicitly provided in config, false otherwise
*/
export const hasExplicitIdentifier = (store: IStore | undefined | null): boolean => {
const userIdentities = store?.SDKConfig?.identifyRequest?.userIdentities;
if (
userIdentities &&
isObject(userIdentities) &&
!isEmpty(userIdentities) &&
Object.values(userIdentities).some(Boolean)
) {
return true;
}
return !!store?.SDKConfig?.deviceId;
};
/**
* Builds the /v1/identify-style envelope (client_sdk, environment,
* request_id, request_timestamp_ms) used to correlate IDSync requests
* across endpoints. `known_identities` is omitted so the caller can
* fold in the search-specific identifiers alongside the envelope.
*/
export const buildIdentitySearchEnvelope = (
environment: Environment,
): Omit<IIdentitySearchRequestBody, 'known_identities'> => ({
client_sdk: {
platform: Constants.platform,
sdk_vendor: Constants.sdkVendor,
sdk_version: Constants.sdkVersion,
},
environment,
request_id: generateUniqueId(),
request_timestamp_ms: Date.now(),
});
/**
* Wires the SDK instance into `sendSearchRequest`: gates on `canLog`,
* builds the `/v1/search` URL and request envelope, and dispatches.
* Lives here so the SDK glue (URL building, opt-out gate, dispatcher
* plumbing) is type-checked instead of being expressed in plain JS.
*/
export const executeSearchRequest = (
mpInstance: IMParticleWebSDKInstance,
workspaceApiKey: string,
knownIdentities: IIdentitySearchKnownIdentities,
callback: IdentitySearchCallback,
): void => {
const { _Helpers, _Store, Logger, _ErrorReportingDispatcher } = mpInstance;
const { identityUrl, isDevelopmentMode } = _Store.SDKConfig;
if (!_Helpers.canLog()) {
Logger.verbose(Messages.InformationMessages.AbandonLogEvent);
if (isFunction(callback)) {
try {
callback({
httpCode: HTTPCodes.loggingDisabledOrMissingAPIKey,
});
} catch (e) {
Logger.error(
'Error invoking search callback: ' +
((e as Error)?.message || String(e)),
);
}
}
return;
}
// The Search endpoint is colocated with /v1/identify under
// identityUrl, so we reuse the same service URL builder. We do
// NOT append the apiKey to the URL — auth is done via x-mp-key.
const serviceUrl: string = _Helpers.createServiceUrl(identityUrl);
const searchUrl: string = serviceUrl + 'search?cb=1';
const environment: Environment = isDevelopmentMode
? 'development'
: 'production';
sendSearchRequest(
knownIdentities,
workspaceApiKey,
() => buildIdentitySearchEnvelope(environment),
searchUrl,
callback,
Logger,
undefined,
_ErrorReportingDispatcher,
);
};