@amedia/user 0.13.38 → 0.13.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +252 -24
  2. package/dist/user.cjs +1 -1
  3. package/dist/user.cjs.map +3 -3
  4. package/dist/user.d.ts +5 -5
  5. package/dist/user.js +1 -1
  6. package/dist/user.js.map +3 -3
  7. package/package.json +10 -8
  8. package/src/actions/authentication.spec.ts +51 -0
  9. package/src/actions/authentication.ts +43 -0
  10. package/src/actions/authorization.spec.ts +369 -0
  11. package/src/actions/authorization.ts +117 -0
  12. package/src/actions/preferences.spec.ts +41 -0
  13. package/src/actions/preferences.ts +41 -0
  14. package/src/actions/storage.ts +22 -0
  15. package/src/actions/userData.spec.ts +133 -0
  16. package/src/actions/userData.ts +68 -0
  17. package/src/autologin/index.spec.ts +239 -0
  18. package/src/autologin/index.ts +92 -0
  19. package/src/autologin/thirdPartyCookie.spec.ts +95 -0
  20. package/src/autologin/thirdPartyCookie.ts +55 -0
  21. package/src/cache/engines/global.spec.ts +62 -0
  22. package/src/cache/engines/global.ts +49 -0
  23. package/src/cache/index.spec.ts +130 -0
  24. package/src/cache/index.ts +48 -0
  25. package/src/cache/types.ts +12 -0
  26. package/src/clients/europa.spec.ts +209 -0
  27. package/src/clients/europa.ts +183 -0
  28. package/src/clients/jupiter.spec.ts +179 -0
  29. package/src/clients/jupiter.ts +119 -0
  30. package/src/clients/mercury.spec.ts +59 -0
  31. package/src/clients/mercury.ts +48 -0
  32. package/src/clients/mercuryLog.spec.ts +20 -0
  33. package/src/clients/mercuryLog.ts +67 -0
  34. package/src/clients/nebula.spec.ts +70 -0
  35. package/src/clients/nebula.ts +83 -0
  36. package/src/clients/pluto.spec.ts +165 -0
  37. package/src/clients/pluto.ts +118 -0
  38. package/src/eventHandlers/activation.ts +36 -0
  39. package/src/eventHandlers/authentication.ts +34 -0
  40. package/src/eventHandlers/eventMap.ts +34 -0
  41. package/src/eventHandlers/state.spec.ts +48 -0
  42. package/src/eventHandlers/state.ts +23 -0
  43. package/src/eventHandlers/storage.spec.ts +114 -0
  44. package/src/eventHandlers/storage.ts +45 -0
  45. package/src/eventHandlers/userAttributes.spec.ts +93 -0
  46. package/src/eventHandlers/userAttributes.ts +31 -0
  47. package/src/exceptions/FetchTimeoutError.ts +8 -0
  48. package/src/exceptions/PaywallError.ts +16 -0
  49. package/src/index-authentcation.spec.ts +26 -0
  50. package/src/index-storage.spec.ts +144 -0
  51. package/src/index-subscription.spec.ts +213 -0
  52. package/src/index.ts +40 -0
  53. package/src/janitor/index.spec.ts +18 -0
  54. package/src/janitor/index.ts +59 -0
  55. package/src/janitor/jobs/accessCookieRefresher.spec.ts +213 -0
  56. package/src/janitor/jobs/accessCookieRefresher.ts +98 -0
  57. package/src/janitor/jobs/daxsubCookie.spec.ts +109 -0
  58. package/src/janitor/jobs/daxsubCookie.ts +38 -0
  59. package/src/janitor/jobs/removeUserStorage.spec.ts +34 -0
  60. package/src/janitor/jobs/removeUserStorage.ts +12 -0
  61. package/src/lib/PaywallUnlockRequest.spec.ts +363 -0
  62. package/src/lib/PaywallUnlockRequest.ts +143 -0
  63. package/src/lib/UserDataRequest.spec.ts +231 -0
  64. package/src/lib/UserDataRequest.ts +267 -0
  65. package/src/lib/cookie.ts +121 -0
  66. package/src/lib/rpc.ts +19 -0
  67. package/src/store/index.spec.ts +49 -0
  68. package/src/store/index.ts +64 -0
  69. package/src/types.ts +22 -0
  70. package/src/utils/customEventWrapper.ts +58 -0
  71. package/src/utils/debouncer.spec.ts +252 -0
  72. package/src/utils/debouncer.ts +123 -0
  73. package/src/utils/deepEquals.ts +42 -0
  74. package/src/utils/expectBootLogs.ts +9 -0
  75. package/src/utils/getGlobalThis.ts +17 -0
  76. package/src/utils/getOrUpdate.spec.ts +166 -0
  77. package/src/utils/getOrUpdate.ts +66 -0
  78. package/src/utils/localhostCheck.ts +10 -0
  79. package/src/utils/location.ts +31 -0
  80. package/src/utils/log.spec.ts +148 -0
  81. package/src/utils/log.ts +124 -0
  82. package/src/utils/loginState.ts +24 -0
  83. package/src/utils/networkError.ts +11 -0
  84. package/src/utils/queue.ts +32 -0
  85. package/src/utils/type.ts +19 -0
  86. package/src/utils/url.spec.ts +33 -0
  87. package/src/utils/url.ts +37 -0
package/src/index.ts ADDED
@@ -0,0 +1,40 @@
1
+ import { dispatch } from './utils/customEventWrapper';
2
+ import * as authentication from './actions/authentication';
3
+ import { AmediaUserEvents } from './eventHandlers/eventMap';
4
+ import { getCurrentUrl } from './utils/url';
5
+ import { runJanitor } from './janitor';
6
+ import { listenForStateRequests } from './eventHandlers/state';
7
+ import { listenForUserAttributeRequests } from './eventHandlers/userAttributes';
8
+ import { listenForStorageRequests } from './eventHandlers/storage';
9
+ import getGlobalThis from './utils/getGlobalThis';
10
+
11
+ export { default as UserDataRequest } from './lib/UserDataRequest';
12
+ export { default as PaywallUnlockRequest } from './lib/PaywallUnlockRequest';
13
+
14
+ /**
15
+ * This will, if necessary, trigger a redirect to www.aid.no and return
16
+ * to the requestedUrl if supplied or the current url before redirecting away if not.
17
+ * @param requestedUrl
18
+ */
19
+ export const goToLoginPage = (requestedUrl?: string) =>
20
+ authentication.login(requestedUrl || getCurrentUrl());
21
+
22
+ export const logout = () => authentication.logout();
23
+
24
+ export const updateStorage = (storage: { [index: string]: Object }) => {
25
+ dispatch(
26
+ new CustomEvent(AmediaUserEvents.UPDATE_STORAGE, { detail: storage })
27
+ );
28
+ };
29
+
30
+ export const saveStorage = (storage: { [index: string]: Object }) => {
31
+ dispatch(new CustomEvent(AmediaUserEvents.SAVE_STORAGE, { detail: storage }));
32
+ };
33
+
34
+ // @ts-ignore
35
+ if (!getGlobalThis().amediaUserTestMode) {
36
+ listenForStateRequests();
37
+ listenForUserAttributeRequests();
38
+ listenForStorageRequests();
39
+ runJanitor();
40
+ }
@@ -0,0 +1,18 @@
1
+ import * as localhostCheck from '../utils/localhostCheck';
2
+ import { runJanitor } from './index';
3
+ import log from '../utils/log';
4
+
5
+ describe('when janitor is started on localhost', () => {
6
+ let logWarnSpy: jest.SpyInstance;
7
+ beforeEach(() => {
8
+ jest.spyOn(localhostCheck, 'isRunningOnLocalhost').mockReturnValue(true);
9
+ logWarnSpy = jest.spyOn(log, 'warn').mockImplementation();
10
+ runJanitor();
11
+ });
12
+
13
+ it('should log a warning', () => {
14
+ expect(logWarnSpy).toBeCalledWith(
15
+ '@amedia/user started on localhost. In this scenario we have no way to resolve any login-, access- or userdata. Expect errors and/or redirects if you try.'
16
+ );
17
+ });
18
+ });
@@ -0,0 +1,59 @@
1
+ import accessCookieRefresher from './jobs/accessCookieRefresher';
2
+ import { removeUserStorage } from './jobs/removeUserStorage';
3
+ import { dispatch, listenWithExclusivity } from '../utils/customEventWrapper';
4
+ import { attemptAutoLoginJob } from '../autologin';
5
+ import daxSubCookieHandler from './jobs/daxsubCookie';
6
+ import log from '../utils/log';
7
+
8
+ const jobs = [
9
+ attemptAutoLoginJob,
10
+ accessCookieRefresher,
11
+ daxSubCookieHandler,
12
+ removeUserStorage,
13
+ ];
14
+
15
+ async function performJobs() {
16
+ if (typeof window === 'undefined') {
17
+ // None of our current jobs make any sense to run in a web worker or other settings without a window object.
18
+ return;
19
+ }
20
+ if (globalThis?.location?.hostname === 'localhost') {
21
+ // Neither if we're running on localhost as this will never be able to resolve any data
22
+ // eslint-disable-next-line no-console
23
+ log.warn(
24
+ '@amedia/user started on localhost. In this scenario we have no way to resolve any login-, access- or userdata. Expect errors and/or redirects if you try.'
25
+ );
26
+ return;
27
+ }
28
+ // eslint-disable-next-line no-restricted-syntax
29
+ for (const job of jobs) {
30
+ // eslint-disable-next-line no-await-in-loop
31
+ await job();
32
+ }
33
+ }
34
+
35
+ enum JanitorEvents {
36
+ LOADED = 'amedia-user.janitor.loaded',
37
+ }
38
+
39
+ declare global {
40
+ interface WindowEventMap {
41
+ [JanitorEvents.LOADED]: CustomEvent<{}>;
42
+ }
43
+ }
44
+
45
+ // We want to ensure that the Janitor is started exactly once. The trick here is to
46
+ // listen to an event end if we receive it exclusively, we know that we are the first
47
+ // to load this script and therefore responsible for running the Janitor once.
48
+ export const runJanitor = async () => {
49
+ let janitorStarted = false;
50
+ listenWithExclusivity(JanitorEvents.LOADED, () => {
51
+ if (janitorStarted) {
52
+ return;
53
+ }
54
+
55
+ janitorStarted = true;
56
+ performJobs();
57
+ });
58
+ dispatch(new CustomEvent(JanitorEvents.LOADED));
59
+ };
@@ -0,0 +1,213 @@
1
+ import accessCookieRefresher from './accessCookieRefresher';
2
+ import * as url from '../../utils/url';
3
+ import UserDataRequest from '../../lib/UserDataRequest';
4
+ import * as cookie from '../../lib/cookie';
5
+ import * as authorization from '../../actions/authorization';
6
+ import store from '../../store';
7
+ import spyOn = jest.spyOn;
8
+ import { AccessFeatures } from '../../clients/jupiter';
9
+
10
+ const mockUuid = '3-1-33-7';
11
+
12
+ beforeEach(() => {
13
+ spyOn(url, 'getCurrentPublicationDomain').mockReturnValue('www.avisnavn.no');
14
+ url.setCurrentHostname('www.avisnavn.no');
15
+ jest
16
+ .spyOn(authorization, 'setUserAccessCookie')
17
+ .mockImplementation(() =>
18
+ Promise.resolve({ success: true, accessFeatures: ['newspaper'] })
19
+ );
20
+ jest
21
+ .spyOn(authorization, 'setNonUserAccessCookie')
22
+ .mockImplementation(() =>
23
+ Promise.resolve({ success: true, accessFeatures: ['newspaper'] })
24
+ );
25
+ });
26
+
27
+ function mockAccessCookie(
28
+ validHours: number,
29
+ uuid: string,
30
+ accessFeatures: AccessFeatures,
31
+ domain: string
32
+ ) {
33
+ const validTo = new Date();
34
+ validTo.setHours(validTo.getHours() + validHours);
35
+ return `signature:${Math.round(
36
+ validTo.getTime() / 1000
37
+ )}:${accessFeatures.join(',')}:${uuid}:${domain}:jupiter`;
38
+ }
39
+
40
+ describe('accessCookieRefresher', () => {
41
+ describe('User is logged in', () => {
42
+ beforeEach(() => {
43
+ jest
44
+ .spyOn(UserDataRequest.prototype, 'subscribe')
45
+ .mockImplementation((callback) => {
46
+ callback({
47
+ attributes: {
48
+ uuid: mockUuid,
49
+ },
50
+ state: {
51
+ isLoggedIn: true,
52
+ },
53
+ });
54
+ });
55
+ store.set('state', { isLoggedIn: true });
56
+ });
57
+
58
+ describe('without any cookies', () => {
59
+ beforeEach(() => {
60
+ jest.spyOn(cookie, 'getCookie').mockReturnValue(null);
61
+ });
62
+ it('Should set user access cookie and non user access cookie', async () => {
63
+ expect(await accessCookieRefresher()).toEqual([undefined, undefined]);
64
+ expect(authorization.setUserAccessCookie).toHaveBeenCalledTimes(1);
65
+ expect(authorization.setNonUserAccessCookie).toHaveBeenCalledTimes(1);
66
+ });
67
+ });
68
+
69
+ describe('with only user access cookie', () => {
70
+ beforeEach(() => {
71
+ jest.spyOn(cookie, 'getCookie').mockImplementation((name) => {
72
+ if (name === 'VSTOKEN') {
73
+ return mockAccessCookie(25, mockUuid, ['newspaper'], 'avisnavn.no');
74
+ }
75
+ return null;
76
+ });
77
+ });
78
+ it('Should set user access cookie and non user access cookie', async () => {
79
+ expect(await accessCookieRefresher()).toEqual([undefined, undefined]);
80
+ expect(authorization.setUserAccessCookie).toHaveBeenCalledTimes(0);
81
+ expect(authorization.setNonUserAccessCookie).toHaveBeenCalledTimes(1);
82
+ });
83
+ });
84
+
85
+ describe('with only non user access cookie', () => {
86
+ beforeEach(() => {
87
+ jest.spyOn(cookie, 'getCookie').mockImplementation((name) => {
88
+ if (name === 'VSTOKEN2') {
89
+ return mockAccessCookie(1, mockUuid, ['newspaper'], 'avisnavn.no');
90
+ }
91
+ return null;
92
+ });
93
+ });
94
+ it('Should set user access cookie and non user access cookie', async () => {
95
+ expect(await accessCookieRefresher()).toEqual([undefined, undefined]);
96
+ expect(authorization.setUserAccessCookie).toHaveBeenCalledTimes(1);
97
+ expect(authorization.setNonUserAccessCookie).toHaveBeenCalledTimes(0);
98
+ });
99
+ });
100
+
101
+ describe('with user access cookie set for another domain', () => {
102
+ beforeEach(() => {
103
+ jest.spyOn(cookie, 'getCookie').mockImplementation((name) => {
104
+ if (name === 'VSTOKEN') {
105
+ return mockAccessCookie(
106
+ 25,
107
+ mockUuid,
108
+ ['newspaper'],
109
+ 'evildomain.no'
110
+ );
111
+ }
112
+ return null;
113
+ });
114
+ });
115
+ it('Should set user access cookie and non user access cookie', async () => {
116
+ expect(await accessCookieRefresher()).toEqual([undefined, undefined]);
117
+ expect(authorization.setUserAccessCookie).toHaveBeenCalledTimes(1);
118
+ });
119
+ });
120
+
121
+ describe('with user access cookie valid for less than 24 hours', () => {
122
+ beforeEach(() => {
123
+ jest.spyOn(cookie, 'getCookie').mockImplementation((name) => {
124
+ if (name === 'VSTOKEN') {
125
+ return mockAccessCookie(23, mockUuid, ['newspaper'], 'avisnavn.no');
126
+ }
127
+ return null;
128
+ });
129
+ });
130
+ it('Should set user access cookie and non user access cookie', async () => {
131
+ expect(await accessCookieRefresher()).toEqual([undefined, undefined]);
132
+ expect(authorization.setUserAccessCookie).toHaveBeenCalledTimes(1);
133
+ });
134
+ });
135
+
136
+ describe('with non user access cookie set for another domain', () => {
137
+ beforeEach(() => {
138
+ jest.spyOn(cookie, 'getCookie').mockImplementation((name) => {
139
+ if (name === 'VSTOKEN2') {
140
+ return mockAccessCookie(
141
+ 25,
142
+ mockUuid,
143
+ ['newspaper'],
144
+ 'evildomain.no'
145
+ );
146
+ }
147
+ return null;
148
+ });
149
+ });
150
+ it('Should set user access cookie and non user access cookie', async () => {
151
+ expect(await accessCookieRefresher()).toEqual([undefined, undefined]);
152
+ expect(authorization.setNonUserAccessCookie).toHaveBeenCalledTimes(1);
153
+ });
154
+ });
155
+
156
+ describe('with non user access cookie valid for less than 30 minutes', () => {
157
+ beforeEach(() => {
158
+ jest.spyOn(cookie, 'getCookie').mockImplementation((name) => {
159
+ if (name === 'VSTOKEN2') {
160
+ return mockAccessCookie(0, mockUuid, ['newspaper'], 'avisnavn.no');
161
+ }
162
+ return null;
163
+ });
164
+ });
165
+ it('Should set user access cookie and non user access cookie', async () => {
166
+ expect(await accessCookieRefresher()).toEqual([undefined, undefined]);
167
+ expect(authorization.setNonUserAccessCookie).toHaveBeenCalledTimes(1);
168
+ });
169
+ });
170
+ });
171
+ describe('User is not logged in', () => {
172
+ beforeEach(() => {
173
+ jest
174
+ .spyOn(UserDataRequest.prototype, 'subscribe')
175
+ .mockImplementation((callback) => {
176
+ callback({
177
+ attributes: {},
178
+ state: {
179
+ isLoggedIn: false,
180
+ },
181
+ });
182
+ });
183
+ store.set('state', { isLoggedIn: false });
184
+ });
185
+ describe('without any cookies', () => {
186
+ beforeEach(() => {
187
+ jest.spyOn(cookie, 'getCookie').mockReturnValue(null);
188
+ });
189
+ it('Should not set any access cookies', async () => {
190
+ expect(await accessCookieRefresher()).toEqual([undefined, undefined]);
191
+ expect(authorization.setUserAccessCookie).toHaveBeenCalledTimes(0);
192
+ expect(authorization.setNonUserAccessCookie).toHaveBeenCalledTimes(0);
193
+ });
194
+ });
195
+ describe('User has both access cookies', () => {
196
+ beforeEach(() => {
197
+ jest
198
+ .spyOn(cookie, 'getCookie')
199
+ .mockImplementation(() =>
200
+ mockAccessCookie(25, mockUuid, ['newspaper'], 'avisnavn.no')
201
+ );
202
+ jest.spyOn(cookie, 'removeCookie').mockImplementation();
203
+ });
204
+ it('Should remove user access cookie', async () => {
205
+ expect(await accessCookieRefresher()).toEqual([undefined, undefined]);
206
+ expect(authorization.setUserAccessCookie).toHaveBeenCalledTimes(0);
207
+ expect(authorization.setNonUserAccessCookie).toHaveBeenCalledTimes(0);
208
+ expect(cookie.removeCookie).toHaveBeenNthCalledWith(1, 'VSTOKEN');
209
+ expect(cookie.removeCookie).toHaveBeenNthCalledWith(2, 'VSTOKEN2');
210
+ });
211
+ });
212
+ });
213
+ });
@@ -0,0 +1,98 @@
1
+ import { getCookie, removeCookie } from '../../lib/cookie';
2
+ import UserDataRequest from '../../lib/UserDataRequest';
3
+ import {
4
+ setNonUserAccessCookie,
5
+ setUserAccessCookie,
6
+ } from '../../actions/authorization';
7
+ import { getCurrentPublicationDomain } from '../../utils/url';
8
+
9
+ const validCookieGenerator = 'jupiter';
10
+
11
+ async function verifyAndSetUserAccessCookie() {
12
+ const cookieName = 'VSTOKEN';
13
+ const publicationDomain = getCurrentPublicationDomain();
14
+ const cookie = getCookie(cookieName);
15
+
16
+ new UserDataRequest()
17
+ .withAttributes(['uuid'])
18
+ .fetch()
19
+ .then(async ({ attributes, state }) => {
20
+ if (state.isLoggedIn === false) {
21
+ if (typeof cookie === 'string') {
22
+ // We don't want logged out users to have lingering VSTOKEN cookies
23
+ removeCookie(cookieName);
24
+ }
25
+ return;
26
+ }
27
+
28
+ if (typeof cookie !== 'string') {
29
+ // We want to set a VSTOKEN cookie for the user so it's ready upon next page load
30
+ await setUserAccessCookie(publicationDomain);
31
+ return;
32
+ }
33
+
34
+ /* The format of the cookie is:
35
+ * <0 - signature>:<1 - timestamp when cookie stops being valid>:<2 - access_features>:<3 - user_id>:<4 - second level domain>:<5 - generator name (jupiter)> */
36
+ const cookieParts = cookie.split(':');
37
+
38
+ const validTo = new Date(parseInt(cookieParts[1], 10) * 1000);
39
+ validTo.setDate(
40
+ validTo.getDate() - 1
41
+ ); /* Set the time one day back so we can update it if it's only valid for one more day */
42
+
43
+ // Make sure that current cookie is not too old, is created for logged in user for this domain by jupiter
44
+ if (
45
+ validTo.getTime() > Date.now() &&
46
+ cookieParts[3] === attributes.uuid &&
47
+ publicationDomain.includes(cookieParts[4]) &&
48
+ cookieParts[5] === validCookieGenerator
49
+ ) {
50
+ return; // Cookie is valid for more than 24 hours, keep it as it is
51
+ }
52
+ await setUserAccessCookie(publicationDomain);
53
+ });
54
+ }
55
+
56
+ function verifyAndSetNonUserAccessCookie() {
57
+ const cookieName = 'VSTOKEN2';
58
+ const publicationDomain = getCurrentPublicationDomain();
59
+ const cookie = getCookie(cookieName);
60
+
61
+ new UserDataRequest()
62
+ .fetch()
63
+ .then(async ({ state: { isLoggedIn } }) => {
64
+ if (isLoggedIn) {
65
+ if (typeof cookie !== 'string') {
66
+ await setNonUserAccessCookie(publicationDomain);
67
+ return;
68
+ }
69
+ /* The format of the cookie is:
70
+ * <0 - signature>:<1 - timestamp when cookie stops being valid>:<2 - access_features>:<3 - uuid>:<4 - second level domain>:<5 - generator name (jupiter)>
71
+ */
72
+ const cookieParts = cookie.split(':');
73
+ const validTo = new Date(parseInt(cookieParts[1], 10) * 1000);
74
+ // // Check that token is valid for the next 30 minutes otherwise we need to update it
75
+ validTo.setMinutes(validTo.getMinutes() - 30);
76
+
77
+ // Make sure that current cookie is not too old and is created for this domain by jupiter
78
+ if (
79
+ validTo.getTime() > Date.now() &&
80
+ publicationDomain.includes(cookieParts[4]) &&
81
+ cookieParts[5] === validCookieGenerator
82
+ ) {
83
+ return;
84
+ }
85
+ await setNonUserAccessCookie(publicationDomain);
86
+ } else {
87
+ removeCookie(cookieName);
88
+ }
89
+ })
90
+ .then(() => {});
91
+ }
92
+
93
+ export default function accessCookieRefresher() {
94
+ return Promise.all([
95
+ verifyAndSetUserAccessCookie(),
96
+ verifyAndSetNonUserAccessCookie(),
97
+ ]);
98
+ }
@@ -0,0 +1,109 @@
1
+ import daxSubCookieHandler from './daxsubCookie';
2
+ import * as cookie from '../../lib/cookie';
3
+ import store from '../../store';
4
+ import { listenForStateRequests } from '../../eventHandlers/state';
5
+ import { listenForUserAttributeRequests } from '../../eventHandlers/userAttributes';
6
+ import UserDataRequest from '../../lib/UserDataRequest';
7
+ import log from '../../utils/log';
8
+
9
+ describe('daxSubCookieHandler', () => {
10
+ beforeEach(() => {
11
+ store.clear();
12
+ spyOn(cookie, 'setCookie');
13
+ spyOn(cookie, 'removeCookie');
14
+
15
+ listenForStateRequests();
16
+ listenForUserAttributeRequests();
17
+ });
18
+
19
+ describe('when fetching user data fails', () => {
20
+ beforeEach(async () => {
21
+ spyOn(UserDataRequest.prototype, 'fetch').and.returnValue(
22
+ Promise.reject(new Error('Could not fetch'))
23
+ );
24
+ spyOn(log, 'warn');
25
+ await daxSubCookieHandler();
26
+ });
27
+
28
+ it('should log error when fetch fails', () => {
29
+ expect(log.warn).toHaveBeenCalledWith(
30
+ `Setting daxsub cookie failed. Error: Could not fetch`,
31
+ new Error('Could not fetch')
32
+ );
33
+ });
34
+ });
35
+
36
+ describe('when user is not logged in', () => {
37
+ beforeEach(async () => {
38
+ store.set('state', { isLoggedIn: false });
39
+ store.set('userAttributes', {
40
+ uuid: null,
41
+ trackingKey: null,
42
+ extraData: {},
43
+ });
44
+ await daxSubCookieHandler();
45
+ });
46
+
47
+ it('Should call removeCookie', () => {
48
+ expect(cookie.removeCookie).toHaveBeenCalled();
49
+ });
50
+
51
+ it('should not call setCookie', () => {
52
+ expect(cookie.setCookie).not.toHaveBeenCalled();
53
+ });
54
+ });
55
+
56
+ describe('when user is logged in', () => {
57
+ beforeEach(async () => {
58
+ store.set('state', { isLoggedIn: true });
59
+ });
60
+
61
+ describe('when has subscription', () => {
62
+ beforeEach(async () => {
63
+ store.set('userAttributes', {
64
+ uuid: 'uuid',
65
+ extraData: {
66
+ customer_keys: 'someString',
67
+ },
68
+ trackingKey: '148d24b2-f28e-4b1c-9958-8abd5066fc59',
69
+ });
70
+ await daxSubCookieHandler();
71
+ });
72
+
73
+ it('Should not call removeCookie', () => {
74
+ expect(cookie.removeCookie).not.toHaveBeenCalled();
75
+ });
76
+
77
+ it('Should set cookie with a_sub_status active', () => {
78
+ expect(cookie.setCookie).toHaveBeenCalledWith(
79
+ 'daxsub',
80
+ 'a_sub_status%3Dactive%26a_user_key%3D148d24b2-f28e-4b1c-9958-8abd5066fc59',
81
+ 1
82
+ );
83
+ });
84
+ });
85
+
86
+ describe('when has no subscription', () => {
87
+ beforeEach(async () => {
88
+ store.set('userAttributes', {
89
+ uuid: 'uuid',
90
+ extraData: {},
91
+ trackingKey: '148d24b2-f28e-4b1c-9958-8abd5066fc59',
92
+ });
93
+ await daxSubCookieHandler();
94
+ });
95
+
96
+ it('Should not call removeCookie', () => {
97
+ expect(cookie.removeCookie).not.toHaveBeenCalled();
98
+ });
99
+
100
+ it('Should set cookie with a_sub_status null', () => {
101
+ expect(cookie.setCookie).toHaveBeenCalledWith(
102
+ 'daxsub',
103
+ 'a_sub_status%3Dnull%26a_user_key%3D148d24b2-f28e-4b1c-9958-8abd5066fc59',
104
+ 1
105
+ );
106
+ });
107
+ });
108
+ });
109
+ });
@@ -0,0 +1,38 @@
1
+ import { setCookie, removeCookie } from '../../lib/cookie';
2
+ import UserDataRequest from '../../lib/UserDataRequest';
3
+ import log from '../../utils/log';
4
+ import { UserAttributes } from '../../types';
5
+
6
+ export function getCookieValue(attributes: UserAttributes) {
7
+ // If user has the customer_keys field set, assume its a paying subscriber and set subscriptionStatus = active.
8
+ const subscriptionStatus = attributes.extraData?.customer_keys
9
+ ? 'active'
10
+ : 'null';
11
+
12
+ const cookieValue = `a_sub_status=${subscriptionStatus}&a_user_key=${attributes.trackingKey}`;
13
+ return cookieValue;
14
+ }
15
+
16
+ function setDaxsubCookie(attributes: UserAttributes) {
17
+ const name = 'daxsub';
18
+ const cookieValue = getCookieValue(attributes);
19
+ const cookieValueEncoded = encodeURIComponent(cookieValue);
20
+ const validTime = 1; // 1 day (24 hours);
21
+ setCookie(name, cookieValueEncoded, validTime);
22
+ }
23
+
24
+ export default function daxSubCookieHandler() {
25
+ return new UserDataRequest()
26
+ .withAttributes(['trackingKey', 'extraData'])
27
+ .fetch({ timeout: 60000 }) // One minute timeout
28
+ .then(({ attributes, state }) => {
29
+ if (!state.isLoggedIn) {
30
+ removeCookie('daxsub');
31
+ return;
32
+ }
33
+ setDaxsubCookie(attributes);
34
+ })
35
+ .catch((e) => {
36
+ log.warn(`Setting daxsub cookie failed. Error: ${e.message}`, e);
37
+ });
38
+ }
@@ -0,0 +1,34 @@
1
+ import store from '../../store';
2
+ import { removeUserStorage } from './removeUserStorage';
3
+ import { listenForStateRequests } from '../../eventHandlers/state';
4
+
5
+ describe('removeUserStorage', () => {
6
+ beforeEach(() => {
7
+ store.clear();
8
+ spyOn(store, 'set').and.callThrough();
9
+ listenForStateRequests();
10
+ removeUserStorage();
11
+ });
12
+
13
+ describe('when logged in', () => {
14
+ beforeEach(() => {
15
+ store.set('state', { isLoggedIn: true });
16
+ });
17
+
18
+ it('should not reset stores', () => {
19
+ expect(store.set).not.toHaveBeenCalledWith('userAttributes', {});
20
+ expect(store.set).not.toHaveBeenCalledWith('storage', {});
21
+ });
22
+ });
23
+
24
+ describe('when not logged in', () => {
25
+ beforeEach(() => {
26
+ store.set('state', { isLoggedIn: false });
27
+ });
28
+
29
+ it('should reset stores', () => {
30
+ expect(store.set).toHaveBeenCalledWith('userAttributes', {});
31
+ expect(store.set).toHaveBeenCalledWith('storage', {});
32
+ });
33
+ });
34
+ });
@@ -0,0 +1,12 @@
1
+ import UserDataRequest from '../../lib/UserDataRequest';
2
+ import store from '../../store';
3
+
4
+ export function removeUserStorage() {
5
+ new UserDataRequest().subscribe(({ state }) => {
6
+ // Need to explicitly check for false here until we have then()
7
+ if (state.isLoggedIn === false) {
8
+ store.set('userAttributes', {});
9
+ store.set('storage', {});
10
+ }
11
+ });
12
+ }