-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathauthorization.ts
More file actions
1201 lines (1078 loc) · 37.7 KB
/
authorization.ts
File metadata and controls
1201 lines (1078 loc) · 37.7 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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable no-console */
/* eslint-disable no-redeclare */
import axios from 'axios';
import {
ENDPOINTS,
IS_PRODUCTION,
STATIC_HEADERS,
SHARED_PREF_UNKNOWN_USER_ID,
RouteConfig,
SHARED_PREFS_CRITERIA,
SHARED_PREF_CONSENT_TIMESTAMP,
SHARED_PREF_EMAIL,
SHARED_PREF_USER_ID,
RETRY_USER_ATTEMPTS
} from '../constants';
import { UnknownUserMerge } from '../unknownUserTracking/unknownUserMerge';
import {
UnknownUserEventManager,
isUnknownUsageTracked,
registerUnknownUserIdSetter
} from '../unknownUserTracking/unknownUserEventManager';
import { IdentityResolution, Options, config } from '../utils/config';
import { getTypeOfAuth, setTypeOfAuth, TypeOfAuth } from '../utils/typeOfAuth';
import AuthorizationToken from '../utils/authorizationToken';
import {
cancelAxiosRequestAndMakeFetch,
getEpochDifferenceInMS,
getEpochExpiryTimeInMS,
isEmail,
ONE_DAY,
ONE_MINUTE,
validateTokenTime
} from './utils';
import { updateUser } from '../users';
import { baseAxiosRequest } from '../request';
import { clearMessages } from '../inapp';
const MAX_TIMEOUT = ONE_DAY;
let authIdentifier: null | string = null;
let userInterceptor: number | null = null;
let authInterceptor: number | null = null;
let apiKey: null | string = null;
let generateJWTGlobal: any = null;
const unknownUserManager = new UnknownUserEventManager();
export interface GenerateJWTPayload {
email?: string;
userID?: string;
}
export interface WithJWT {
setEmail: (
email: string,
identityResolution?: IdentityResolution
) => Promise<string>;
setUserID: (
userId: string,
identityResolution?: IdentityResolution
) => Promise<string>;
logout: () => void;
refreshJwtToken: (authTypes: string) => Promise<string>;
clearRefresh: () => void;
setVisitorUsageTracked: (consent: boolean) => void;
clearVisitorEventsAndUserData: () => void;
}
export interface WithoutJWT {
setEmail: (
email: string,
identityResolution?: IdentityResolution
) => Promise<string>;
setUserID: (
userId: string,
identityResolution?: IdentityResolution
) => Promise<string>;
logout: () => void;
setNewAuthToken: (newToken?: string) => void;
clearAuthToken: () => void;
setVisitorUsageTracked: (consent: boolean) => void;
clearVisitorEventsAndUserData: () => void;
}
const doesRequestUrlContain = (routeConfig: RouteConfig) =>
Object.entries(ENDPOINTS).some(
(entry) =>
routeConfig.route === entry[1].route &&
routeConfig.body === entry[1].body &&
routeConfig.current === entry[1].current &&
routeConfig.nestedUser === entry[1].nestedUser
);
const addUserIdToRequest = (userId: string) => {
setTypeOfAuth('userID');
authIdentifier = userId;
localStorage.setItem(SHARED_PREF_USER_ID, userId);
if (typeof userInterceptor === 'number') {
baseAxiosRequest.interceptors.request.eject(userInterceptor);
}
/*
endpoints that use _userId_ payload prop in POST/PUT requests
*/
userInterceptor = baseAxiosRequest.interceptors.request.use((config) => {
if (
doesRequestUrlContain({
route: config?.url ?? '',
body: true,
current: true,
nestedUser: true
})
) {
return {
...config,
data: {
...(config.data || {}),
currentUserId: userId
}
};
}
/*
endpoints that use _userId_ payload prop in POST/PUT requests
*/
if (
doesRequestUrlContain({
route: config?.url ?? '',
body: true,
current: false,
nestedUser: false
})
) {
return {
...config,
data: {
...(config.data || {}),
userId
}
};
}
/*
endpoints that use _userId_ payload prop in POST/PUT requests nested in { user: {} }
*/
if (
doesRequestUrlContain({
route: config?.url ?? '',
body: true,
current: false,
nestedUser: true
})
) {
return {
...config,
data: {
...(config.data || {}),
user: {
...(config.data.user || {}),
userId
}
}
};
}
/*
endpoints that use _userId_ query param in GET requests
*/
if (
doesRequestUrlContain({
route: config?.url ?? '',
body: false,
current: false,
nestedUser: false
})
) {
return {
...config,
params: {
...(config.params || {}),
userId
}
};
}
return config;
});
};
export const setUnknownUserId = async (userId: string) => {
const unknownUsageTracked = isUnknownUsageTracked();
if (!unknownUsageTracked) return;
let token: null | string = null;
if (generateJWTGlobal) {
token = await generateJWTGlobal({ userID: userId });
}
if (token) {
const authorizationToken = new AuthorizationToken();
authorizationToken.setToken(token);
}
// Only set up API key interceptor if in JWT mode
// In non-JWT mode, this is already handled by initialization
if (generateJWTGlobal) {
// Clear any existing auth interceptor first
if (typeof authInterceptor === 'number') {
baseAxiosRequest.interceptors.request.eject(authInterceptor);
}
// Store the interceptor ID in the global variable
authInterceptor = baseAxiosRequest.interceptors.request.use((config) => {
config.headers.set('Api-Key', apiKey);
return config;
});
}
addUserIdToRequest(userId);
localStorage.setItem(SHARED_PREF_UNKNOWN_USER_ID, userId);
};
registerUnknownUserIdSetter(setUnknownUserId);
const clearUnknownUser = () => {
localStorage.removeItem(SHARED_PREF_UNKNOWN_USER_ID);
};
const getUnknownUserId = () => {
if (config.getConfig('enableUnknownActivation')) {
const unknownUser = localStorage.getItem(SHARED_PREF_UNKNOWN_USER_ID);
return unknownUser === undefined ? null : unknownUser;
}
return null;
};
const initializeUserId = (userId: string) => {
addUserIdToRequest(userId);
// Note: clearUnknownUser() moved to happen after merge attempt
};
const addEmailToRequest = (email: string) => {
setTypeOfAuth('email');
authIdentifier = email;
localStorage.setItem(SHARED_PREF_EMAIL, email);
if (typeof userInterceptor === 'number') {
baseAxiosRequest.interceptors.request.eject(userInterceptor);
}
userInterceptor = baseAxiosRequest.interceptors.request.use((config) => {
/*
endpoints that use _currentEmail_ payload prop in POST/PUT requests
*/
if (
doesRequestUrlContain({
route: config?.url ?? '',
body: true,
current: true,
nestedUser: true
})
) {
return {
...config,
data: {
...(config.data || {}),
currentEmail: email
}
};
}
/*
endpoints that use _email_ payload prop in POST/PUT requests
*/
if (
doesRequestUrlContain({
route: config?.url ?? '',
body: true,
current: false,
nestedUser: false
})
) {
return {
...config,
data: {
...(config.data || {}),
email
}
};
}
/*
endpoints that use _userId_ payload prop in POST/PUT requests nested in { user: {} }
*/
if (
doesRequestUrlContain({
route: config?.url ?? '',
body: true,
current: false,
nestedUser: true
})
) {
return {
...config,
data: {
...(config.data || {}),
user: {
...(config.data.user || {}),
email
}
}
};
}
/*
endpoints that use _email_ query param in GET requests
*/
if (
doesRequestUrlContain({
route: config?.url ?? '',
body: false,
current: false,
nestedUser: false
})
) {
return {
...config,
params: {
...(config.params || {}),
email
}
};
}
return config;
});
};
const initializeEmailUser = (email: string) => {
addEmailToRequest(email);
// Note: clearUnknownUser() moved to happen after merge attempt
};
const syncEvents = () => {
if (config.getConfig('enableUnknownActivation')) {
unknownUserManager.syncEvents();
}
};
const handleConsentTracking = (
isUserKnown = false,
isMergeOperation = false
) => {
if (config.getConfig('enableUnknownActivation')) {
unknownUserManager.handleConsentTracking(isUserKnown, isMergeOperation);
}
};
const getIdentityResolutionBehavior = (
identityResolution?: IdentityResolution
) => {
const identityResolutionConfig = config.getConfig('identityResolution');
return {
merge:
identityResolution?.mergeOnUnknownToKnown ??
identityResolutionConfig?.mergeOnUnknownToKnown,
replay:
identityResolution?.replayOnVisitorToKnown ??
identityResolutionConfig?.replayOnVisitorToKnown
};
};
const setAuthInterceptor = (
authInterceptor: number | null,
authToken: string
) => {
if (typeof authInterceptor === 'number') {
/** Clear previously cached interceptor function */
baseAxiosRequest.interceptors.request.eject(authInterceptor);
}
/** Set auth token to interceptor for all requests */
return baseAxiosRequest.interceptors.request.use((config) => {
config.headers.set('Api-Key', authToken);
return config;
});
};
export function initialize(
authToken: string,
generateJWT: (payload: GenerateJWTPayload) => Promise<string>
): WithJWT;
export function initialize(authToken: string): WithoutJWT;
export function initialize(
authToken: string,
generateJWT?: (payload: GenerateJWTPayload) => Promise<string>
) {
apiKey = authToken;
generateJWTGlobal = generateJWT;
const logLevel = config.getConfig('logLevel');
if (!generateJWT && IS_PRODUCTION) {
/* only let people use non-JWT mode if running the app locally */
if (logLevel === 'verbose') {
return console.error(
'Please provide a Promise method for generating a JWT token.'
);
}
return null;
}
/*
Always set the API key interceptor during initialization.
This is needed for endpoints like /unknownuser/list that require the API key
but are called before user authentication (and thus before JWT generation).
*/
authInterceptor = setAuthInterceptor(null, authToken);
const userInterceptor: number | null = null;
let responseInterceptor: number | null = null;
/**
method that sets a timer one minute before JWT expiration
@param { string } jwt - JWT token to decode
@param { (...args: any ) => Promise<any> } callback - promise to invoke before expiry
*/
const createTokenExpirationTimer = () => {
let timer: NodeJS.Timeout | null;
// eslint-disable-next-line consistent-return
return (jwt: string, callback?: (...args: any) => Promise<any>) => {
if (timer) {
/* clear existing timeout on JWT refresh */
clearTimeout(timer);
timer = null;
}
if (callback) {
const expTime = getEpochExpiryTimeInMS(jwt);
const millisecondsToExpired = getEpochDifferenceInMS(
Date.now(),
expTime
);
if (validateTokenTime(millisecondsToExpired)) {
return console.warn(
'Could not refresh JWT. Try generating the token again.'
);
}
if (millisecondsToExpired < MAX_TIMEOUT) {
timer = setTimeout(
() =>
/* get new token */
callback().catch((e: any) => {
console.warn(e);
console.warn(
'Could not refresh JWT. Try identifying the user again.'
);
}),
/* try to refresh one minute until expiry */
millisecondsToExpired - ONE_MINUTE
);
}
}
};
};
const handleTokenExpiration = createTokenExpirationTimer();
const tryUser = () => {
let createUserAttempts = 0;
return async function tryUserNTimes(): Promise<any> {
try {
return await updateUser({});
} catch (e) {
if (createUserAttempts < RETRY_USER_ATTEMPTS) {
createUserAttempts += 1;
return tryUserNTimes();
}
return Promise.reject(
new Error(`could not create user after ${createUserAttempts} tries`)
);
}
};
};
const enableUnknownTracking = () => {
try {
if (config.getConfig('enableUnknownActivation')) {
unknownUserManager.getUnknownCriteria();
unknownUserManager.updateUnknownSession();
const unknownUserId = getUnknownUserId();
if (unknownUserId !== null) {
// This block will restore the unknown userID from localstorage
setUnknownUserId(unknownUserId);
}
}
} catch (error) {
console.warn(error);
}
};
const tryMergeUser = async (
emailOrUserId: string,
isEmail: boolean,
merge?: boolean
): Promise<{ success: boolean; mergePerformed: boolean }> => {
const enableUnknownActivation = config.getConfig('enableUnknownActivation');
const destinationUserId = isEmail ? null : emailOrUserId;
const destinationEmail = isEmail ? emailOrUserId : null;
// Only merge if there's an unknown user that was successfully created via /session
const unknownUserId = getUnknownUserId();
if (unknownUserId !== null && merge && enableUnknownActivation) {
const unknownUserMerge = new UnknownUserMerge();
try {
await unknownUserMerge.mergeUnknownUser(
unknownUserId,
destinationUserId,
destinationEmail
);
return Promise.resolve({ success: true, mergePerformed: true });
} catch (error) {
return Promise.reject(new Error(`merging failed: ${error}`));
}
}
// promise resolves here because merging is not needed
return Promise.resolve({ success: true, mergePerformed: false });
};
if (!generateJWT) {
enableUnknownTracking();
/* we want to set a normal non-JWT enabled API key */
return {
setNewAuthToken: (newToken: string) => {
if (typeof authInterceptor === 'number') {
/* clear previously cached interceptor function */
baseAxiosRequest.interceptors.request.eject(authInterceptor);
}
authInterceptor = baseAxiosRequest.interceptors.request.use(
(config) => {
config.headers.set('Api-Key', newToken);
return config;
}
);
},
clearAuthToken: () => {
/* might be 0 which is a falsy value */
if (typeof authInterceptor === 'number') {
/* clear previously cached interceptor function */
baseAxiosRequest.interceptors.request.eject(authInterceptor);
}
},
setEmail: async (
email: string,
identityResolution?: IdentityResolution
) => {
clearMessages();
authInterceptor = setAuthInterceptor(authInterceptor, authToken);
try {
const { merge, replay } =
getIdentityResolutionBehavior(identityResolution);
// Set up user authentication first so merge API can authenticate
initializeEmailUser(email);
const result = await tryMergeUser(email, true, merge);
if (result.success) {
// Clear unknown user after merge attempt (successful or skipped)
clearUnknownUser();
if (replay) {
await handleConsentTracking(true, result.mergePerformed);
syncEvents();
} else {
unknownUserManager.removeUnknownSessionCriteriaData();
}
return Promise.resolve(email);
}
return Promise.resolve(email);
} catch (error) {
// here we will not sync events but just bubble up error of merge
return Promise.reject(new Error(`merging failed: ${error}`));
}
},
setUserID: async (
userId: string,
identityResolution?: IdentityResolution
) => {
clearMessages();
try {
const { merge, replay } =
getIdentityResolutionBehavior(identityResolution);
// Initialize user authentication first, then create user profile
initializeUserId(userId);
await tryUser()();
const result = await tryMergeUser(userId, false, merge);
if (result.success) {
// Clear unknown user after merge attempt (successful or skipped)
clearUnknownUser();
if (replay) {
await handleConsentTracking(true, result.mergePerformed);
syncEvents();
} else {
unknownUserManager.removeUnknownSessionCriteriaData();
}
return Promise.resolve(userId);
}
return Promise.resolve(userId);
} catch (error) {
// here we will not sync events but just bubble up error of merge
return Promise.reject(new Error(`merging failed: ${error}`));
}
},
logout: () => {
unknownUserManager.removeUnknownSessionCriteriaData();
setTypeOfAuth(null);
authIdentifier = null;
localStorage.removeItem(SHARED_PREF_EMAIL);
localStorage.removeItem(SHARED_PREF_USER_ID);
localStorage.removeItem(SHARED_PREF_CONSENT_TIMESTAMP);
/* clear fetched in-app messages */
clearMessages();
const authorizationToken = new AuthorizationToken();
authorizationToken.clearToken();
if (typeof authInterceptor === 'number') {
/* stop adding auth token to requests */
baseAxiosRequest.interceptors.request.eject(authInterceptor);
}
if (typeof userInterceptor === 'number') {
/* stop adding JWT to requests */
baseAxiosRequest.interceptors.request.eject(userInterceptor);
}
/*
Re-establish the API key interceptor for unknown user endpoints
This ensures /unknownuser/list and similar endpoints continue to work after logout
*/
if (apiKey) {
authInterceptor = setAuthInterceptor(null, apiKey);
}
},
setVisitorUsageTracked: (consent: boolean) => {
/* if consent is true, we want to clear unknown user data and start tracking */
if (consent) {
unknownUserManager.removeUnknownSessionCriteriaData();
localStorage.removeItem(SHARED_PREFS_CRITERIA);
// Store consent timestamp when user grants consent
const existingConsent = localStorage.getItem(
SHARED_PREF_CONSENT_TIMESTAMP
);
if (!existingConsent) {
localStorage.setItem(
SHARED_PREF_CONSENT_TIMESTAMP,
Date.now().toString()
);
}
enableUnknownTracking();
} else {
/* if consent is false, we want to stop tracking and clear unknown user data */
const unknownUsageTracked = isUnknownUsageTracked();
if (unknownUsageTracked) {
unknownUserManager.removeUnknownSessionCriteriaData();
localStorage.removeItem(SHARED_PREFS_CRITERIA);
localStorage.removeItem(SHARED_PREF_UNKNOWN_USER_ID);
localStorage.removeItem(SHARED_PREF_CONSENT_TIMESTAMP);
setTypeOfAuth(null);
authIdentifier = null;
/* clear fetched in-app messages */
clearMessages();
}
}
},
clearVisitorEventsAndUserData: () => {
unknownUserManager.removeUnknownSessionCriteriaData();
clearUnknownUser();
}
};
}
const authorizationToken = new AuthorizationToken();
/*
We're using a JWT enabled API key
callback is assumed to be some sort of GET /api/generate-jwt
*/
const doRequest = (payload: { email?: string; userID?: string }) => {
authorizationToken.clearToken();
/* clear any token interceptor if any exists */
if (typeof authInterceptor === 'number') {
baseAxiosRequest.interceptors.request.eject(authInterceptor);
}
if (typeof responseInterceptor === 'number') {
baseAxiosRequest.interceptors.response.eject(responseInterceptor);
}
return generateJWT(payload)
.then((token) => {
const authorizationToken = new AuthorizationToken();
authorizationToken.setToken(token);
/* set JWT token and auth token headers */
authInterceptor = baseAxiosRequest.interceptors.request.use(
(config) => {
if ((config as any)?.sendBeacon) {
/*
send fetch request instead solely so we can use the "keepalive" flag.
This is used purely for one use-case only - when the user clicks a link
that is going to navigate the browser tab to a new page/site and we need
to still call POST /trackInAppClick.
Normally, since the page is going somewhere new, the browser would navigate away
and cancel any in-flight requests and not fulfill them, but with the fetch API's
"keepalive" flag, it will continue the request without blocking the main thread.
We can't do this with Axios because it's built upon XHR and that doesn't support
"keepalive" so we fall back to the fetch API
*/
const cancelConfig = cancelAxiosRequestAndMakeFetch(
config,
{ email: payload.email, userID: payload.userID },
token,
authToken
);
return cancelConfig;
}
config.headers.set('Api-Key', authToken);
return config;
}
);
responseInterceptor = baseAxiosRequest.interceptors.response.use(
(config) => {
if (
doesRequestUrlContain({
route: config?.config?.url ?? '',
body: true,
current: true,
nestedUser: true
})
) {
try {
/*
if the customer just called the POST /users/updateEmail
that means their JWT needs to be updated to include this new
email as well, so we run their JWT generation method and
set a new token on the axios interceptor
*/
const newEmail = JSON.parse(config.config.data)?.newEmail;
const payloadToPass =
getTypeOfAuth() === 'email'
? { email: newEmail }
: { userID: authIdentifier ?? '' };
return generateJWT(payloadToPass).then((newToken) => {
const authorizationToken = new AuthorizationToken();
authorizationToken.setToken(newToken);
/*
clear any existing interceptors that are adding user info
or API keys
*/
if (typeof authInterceptor === 'number') {
/* stop adding auth token to requests */
baseAxiosRequest.interceptors.request.eject(
authInterceptor
);
}
if (typeof userInterceptor === 'number') {
/* stop adding JWT to requests */
baseAxiosRequest.interceptors.request.eject(
userInterceptor
);
}
/* add the new JWT to all outgoing requests */
authInterceptor = baseAxiosRequest.interceptors.request.use(
(config) => {
if ((config as any)?.sendBeacon) {
/*
send fetch request instead solely so we can use the "keepalive" flag.
This is used purely for one use-case only - when the user clicks a link
that is going to navigate the browser tab to a new page/site and we need
to still call POST /trackInAppClick.
Normally, since the page is going somewhere new, the browser would just
navigate away and cancel any in-flight requests and not fulfill them,
but with the fetch API's "keepalive" flag, it will continue the request
without blocking the main thread.
We can't do this with Axios because it's built upon XHR and that
doesn't support "keepalive" so we fall back to the fetch API
*/
return cancelAxiosRequestAndMakeFetch(
config,
{ email: newEmail },
newToken,
authToken
);
}
config.headers.set('Api-Key', authToken);
config.headers.set('Authorization', `Bearer ${newToken}`);
return config;
}
);
/* add the new email to all outgoing requests */
addEmailToRequest(newEmail);
/*
set up a new timer for when the JWT expires to regenerate
a new one encoded with the new email address.
*/
/*
important here to clear the timer first since there was one set up
previously the first time the JWT was generated.
handleTokenExpiration will clear the timeout for us.
*/
handleTokenExpiration(newToken, () =>
/* re-run the JWT generation */
doRequest(payloadToPass).catch((e: any) => {
console.warn(e);
console.warn(
'Could not refresh JWT. Try identifying the user again.'
);
})
);
return config;
});
} catch {
return config;
}
}
return config;
},
(error) => {
/*
adds a status code 401 callback to try and get a new JWT
key if the Iterable API told us the JWT is invalid.
*/
if (error?.response?.status === 401) {
return generateJWT(payload)
.then((newToken) => {
const authorizationToken = new AuthorizationToken();
authorizationToken.setToken(newToken);
if (authInterceptor) {
baseAxiosRequest.interceptors.request.eject(
authInterceptor
);
}
authInterceptor = baseAxiosRequest.interceptors.request.use(
(config) => {
if ((config as any)?.sendBeacon) {
/*
send fetch request instead solely so we can use the "keepalive" flag.
This is used purely for one use-case only - when the user clicks a link
that is going to navigate the browser tab to a new page/site and we need
to still call POST /trackInAppClick.
Normally, since the page is going somewhere new, the browser would just
navigate away and cancel any in-flight requests and not fulfill
them, but with the fetch API's "keepalive" flag, it will continue
the request without blocking the main thread.
We can't do this with Axios because it's built upon XHR and that
doesn't support "keepalive" so we fall back to the fetch API
*/
return cancelAxiosRequestAndMakeFetch(
config,
{ email: payload.email, userID: payload.userID },
newToken,
authToken
);
}
config.headers.set('Api-Key', authToken);
config.headers.set('Authorization', `Bearer ${newToken}`);
return config;
}
);
/*
finally, after the new JWT is generated, try the original
request that failed again.
*/
return axios({
...error.config,
headers: {
...error.config.headers,
...STATIC_HEADERS,
'Api-Key': authToken,
Authorization: `Bearer ${newToken}`
}
});
})
.catch((e: any) =>
/*
if the JWT generation failed,
just abort with a Promise rejection.
*/
Promise.reject(e)
);
}
return Promise.reject(error);
}
);
handleTokenExpiration(token, () =>
/* re-run the JWT generation */
doRequest(payload).catch((e: any) => {
if (logLevel === 'verbose') {
console.warn(e);
console.warn(
'Could not refresh JWT. Try identifying the user again.'
);
}
})
);
return token;
})
.catch((error) => {
/* clear interceptor */
const authorizationToken = new AuthorizationToken();
authorizationToken.clearToken();
if (typeof authInterceptor === 'number') {
baseAxiosRequest.interceptors.request.eject(authInterceptor);
}
return Promise.reject(error);
});
};
enableUnknownTracking();
return {
clearRefresh: () => {
/* this will just clear the existing timeout */
handleTokenExpiration('');
},
setEmail: async (
email: string,
identityResolution?: IdentityResolution
) => {
/* clear previous user */
clearMessages();
try {
const { merge, replay } =
getIdentityResolutionBehavior(identityResolution);
try {
return doRequest({ email })
.then(async (token) => {
// Set up user context first
initializeEmailUser(email);
// Create user profile first before attempting merge
await tryUser()();
const result = await tryMergeUser(email, true, merge);
if (result.success) {
// Clear unknown user after merge attempt (successful or skipped)
clearUnknownUser();
if (replay) {
await handleConsentTracking(true, result.mergePerformed);
syncEvents();
} else {
unknownUserManager.removeUnknownSessionCriteriaData();
}
return token;
}
return token;
})
.catch((e) => {
if (logLevel === 'verbose') {
console.warn(