@amedia/user 0.14.18 → 0.14.19

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 (85) hide show
  1. package/package.json +2 -3
  2. package/src/actions/authentication.spec.ts +0 -51
  3. package/src/actions/authentication.ts +0 -49
  4. package/src/actions/authorization.spec.ts +0 -377
  5. package/src/actions/authorization.ts +0 -120
  6. package/src/actions/preferences.spec.ts +0 -41
  7. package/src/actions/preferences.ts +0 -41
  8. package/src/actions/storage.ts +0 -22
  9. package/src/actions/userData.spec.ts +0 -133
  10. package/src/actions/userData.ts +0 -68
  11. package/src/autologin/index.spec.ts +0 -264
  12. package/src/autologin/index.ts +0 -113
  13. package/src/autologin/thirdPartyCookie.spec.ts +0 -95
  14. package/src/autologin/thirdPartyCookie.ts +0 -55
  15. package/src/cache/engines/global.spec.ts +0 -62
  16. package/src/cache/engines/global.ts +0 -49
  17. package/src/cache/index.spec.ts +0 -132
  18. package/src/cache/index.ts +0 -48
  19. package/src/cache/types.ts +0 -12
  20. package/src/clients/europa.spec.ts +0 -209
  21. package/src/clients/europa.ts +0 -183
  22. package/src/clients/jupiter.spec.ts +0 -178
  23. package/src/clients/jupiter.ts +0 -119
  24. package/src/clients/mercury.spec.ts +0 -126
  25. package/src/clients/mercury.ts +0 -105
  26. package/src/clients/mercuryLog.spec.ts +0 -20
  27. package/src/clients/mercuryLog.ts +0 -67
  28. package/src/clients/nebula.spec.ts +0 -70
  29. package/src/clients/nebula.ts +0 -83
  30. package/src/clients/pluto.spec.ts +0 -262
  31. package/src/clients/pluto.ts +0 -126
  32. package/src/eventHandlers/activation.ts +0 -40
  33. package/src/eventHandlers/authentication.ts +0 -34
  34. package/src/eventHandlers/eventMap.ts +0 -40
  35. package/src/eventHandlers/navigation.spec.ts +0 -189
  36. package/src/eventHandlers/navigation.ts +0 -58
  37. package/src/eventHandlers/state.spec.ts +0 -48
  38. package/src/eventHandlers/state.ts +0 -23
  39. package/src/eventHandlers/storage.spec.ts +0 -114
  40. package/src/eventHandlers/storage.ts +0 -45
  41. package/src/eventHandlers/userAttributes.spec.ts +0 -93
  42. package/src/eventHandlers/userAttributes.ts +0 -31
  43. package/src/exceptions/FetchTimeoutError.ts +0 -8
  44. package/src/exceptions/PaywallError.ts +0 -16
  45. package/src/index-authentcation.spec.ts +0 -26
  46. package/src/index-storage.spec.ts +0 -144
  47. package/src/index-subscription.spec.ts +0 -213
  48. package/src/index.ts +0 -46
  49. package/src/janitor/index.spec.ts +0 -18
  50. package/src/janitor/index.ts +0 -60
  51. package/src/janitor/jobs/accessCookieRefresher.spec.ts +0 -213
  52. package/src/janitor/jobs/accessCookieRefresher.ts +0 -96
  53. package/src/janitor/jobs/daxsubCookie.spec.ts +0 -109
  54. package/src/janitor/jobs/daxsubCookie.ts +0 -38
  55. package/src/janitor/jobs/removeUserStorage.spec.ts +0 -34
  56. package/src/janitor/jobs/removeUserStorage.ts +0 -12
  57. package/src/lib/PaywallUnlockRequest.spec.ts +0 -446
  58. package/src/lib/PaywallUnlockRequest.ts +0 -161
  59. package/src/lib/UserDataRequest.spec.ts +0 -231
  60. package/src/lib/UserDataRequest.ts +0 -267
  61. package/src/lib/cookie.ts +0 -121
  62. package/src/lib/rpc.ts +0 -19
  63. package/src/store/index.spec.ts +0 -49
  64. package/src/store/index.ts +0 -66
  65. package/src/types.ts +0 -22
  66. package/src/utils/customEventWrapper.spec.ts +0 -237
  67. package/src/utils/customEventWrapper.ts +0 -77
  68. package/src/utils/debouncer.spec.ts +0 -252
  69. package/src/utils/debouncer.ts +0 -123
  70. package/src/utils/deepEquals.ts +0 -42
  71. package/src/utils/expectBootLogs.ts +0 -9
  72. package/src/utils/getGlobalThis.ts +0 -17
  73. package/src/utils/getOrUpdate.spec.ts +0 -166
  74. package/src/utils/getOrUpdate.ts +0 -66
  75. package/src/utils/localhostCheck.ts +0 -10
  76. package/src/utils/location.spec.ts +0 -61
  77. package/src/utils/location.ts +0 -16
  78. package/src/utils/log.spec.ts +0 -177
  79. package/src/utils/log.ts +0 -112
  80. package/src/utils/loginState.ts +0 -24
  81. package/src/utils/networkError.ts +0 -11
  82. package/src/utils/queue.ts +0 -32
  83. package/src/utils/type.ts +0 -19
  84. package/src/utils/url.spec.ts +0 -33
  85. package/src/utils/url.ts +0 -37
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amedia/user",
3
- "version": "0.14.18",
3
+ "version": "0.14.19",
4
4
  "description": "Client lib for working with aID user and associated data",
5
5
  "repository": "https://github.com/amedia/amedia-user-js",
6
6
  "author": "Amedia Utvikling (ID og data)",
@@ -12,8 +12,7 @@
12
12
  }
13
13
  },
14
14
  "files": [
15
- "dist/*",
16
- "src/*"
15
+ "dist/*"
17
16
  ],
18
17
  "typings": "dist/user.d.ts",
19
18
  "scripts": {
@@ -1,51 +0,0 @@
1
- import * as url from '../utils/url';
2
- import * as location from '../utils/location';
3
- import { login } from './authentication';
4
-
5
- beforeEach(() => {
6
- spyOn(url, 'getCurrentUrl').and.returnValue('https://www.telen.no/artikkel/');
7
- spyOn(url, 'getCurrentSiteDomain').and.returnValue('www.telen.no');
8
- spyOn(location, 'navigateTo');
9
- });
10
-
11
- describe('authentication', () => {
12
- describe('goToLoginPage', () => {
13
- describe('when using URL or string for param', () => {
14
- it('should return expected url for string', () => {
15
- login('https://my.url/');
16
- expect(location.navigateTo).toHaveBeenCalledWith(
17
- 'https://www.aid.no/aid/logg_inn/www.telen.no/?requestedUrl=https%3A%2F%2Fmy.url%2F'
18
- );
19
- });
20
- it('should return expected url for URL', () => {
21
- login(new URL('https://my.url'));
22
- expect(location.navigateTo).toHaveBeenCalledWith(
23
- 'https://www.aid.no/aid/logg_inn/www.telen.no/?requestedUrl=https%3A%2F%2Fmy.url%2F'
24
- );
25
- });
26
- });
27
- describe('when changing environment', () => {
28
- it('should resolve dev env', () => {
29
- spyOn(url, 'getCurrentEnvironment').and.returnValue('localhost');
30
- login('current');
31
- expect(location.navigateTo).toHaveBeenCalledWith(
32
- 'https://www.aid.no.localhost.api.no/aid/logg_inn/www.telen.no/?requestedUrl=current'
33
- );
34
- });
35
- it('should resolve snap5 env', () => {
36
- spyOn(url, 'getCurrentEnvironment').and.returnValue('snap5');
37
- login('current');
38
- expect(location.navigateTo).toHaveBeenCalledWith(
39
- 'https://www-snap5.aid.no/aid/logg_inn/www.telen.no/?requestedUrl=current'
40
- );
41
- });
42
- it('should resolve prod env', () => {
43
- spyOn(url, 'getCurrentEnvironment').and.returnValue('');
44
- login('current');
45
- expect(location.navigateTo).toHaveBeenCalledWith(
46
- 'https://www.aid.no/aid/logg_inn/www.telen.no/?requestedUrl=current'
47
- );
48
- });
49
- });
50
- });
51
- });
@@ -1,49 +0,0 @@
1
- import { getCurrentSession, removeSession } from '../clients/pluto';
2
- import cache from '../cache';
3
- import { getRPCClient } from '../lib/rpc';
4
- import { removeCookie } from '../lib/cookie';
5
- import { getAidDomain, getCurrentSiteDomain } from '../utils/url';
6
- import log from '../utils/log';
7
- import { UserAttributes } from '../types';
8
- import { navigateTo } from '../utils/location';
9
-
10
- export const loginUrl = (requestedUrl: URL | string) => {
11
- const url = new URL(
12
- `https://${getAidDomain()}/aid/logg_inn/${getCurrentSiteDomain()}/`
13
- );
14
- url.searchParams.set(
15
- 'requestedUrl',
16
- requestedUrl instanceof URL ? requestedUrl.href : requestedUrl
17
- );
18
- return url;
19
- };
20
-
21
- export const login = (requestedUrl: URL | string) => {
22
- const url = loginUrl(requestedUrl);
23
- navigateTo(url.href);
24
- };
25
-
26
- function clearCookies() {
27
- removeCookie('VSTOKEN');
28
- removeCookie('VSTOKEN2');
29
- removeCookie('aid.session');
30
- removeCookie('aid_invitation_code');
31
- removeCookie('aid-reload-article');
32
- removeCookie('daxsub');
33
- }
34
-
35
- export const logout = async () =>
36
- // TODO: It now clears the entire cache. Might be too aggressive.
37
- Promise.all([removeSession(getCurrentSiteDomain()), cache.clear()])
38
- .then(() => {
39
- // TODO This should be separated from logout and instead be setup to listen on state changes on storage
40
- getRPCClient().userAuthenticated(false);
41
- clearCookies();
42
- // In addition to removing the regular cookies we also want to remove VSTOKEN2 on explicit logout
43
- removeCookie('VSTOKEN2');
44
- })
45
- .catch((reason) => {
46
- log.error('Failure while logging out', reason);
47
- });
48
-
49
- export const getSession = (): Promise<UserAttributes> => getCurrentSession();
@@ -1,377 +0,0 @@
1
- /**
2
- * @jest-environment jsdom
3
- */
4
-
5
- import {
6
- activate,
7
- getAccess,
8
- hasAccess,
9
- hasRecentlyPerformedPaywallReload,
10
- setAccessCookies,
11
- setHasPerformedPaywallReload,
12
- setNonUserAccessCookie,
13
- setUserAccessCookie,
14
- } from './authorization';
15
- import * as jupiter from '../clients/jupiter';
16
- import * as cookie from '../lib/cookie';
17
- import * as url from '../utils/url';
18
- import * as mercury from '../clients/mercury';
19
- import * as authentication from './authentication';
20
- import { removeAllCookies } from '../lib/cookie';
21
- import { AccessFeatures } from '../clients/jupiter';
22
-
23
- const siteDomain = 'www.avisnavn.no';
24
-
25
- beforeEach(() => {
26
- removeAllCookies();
27
- jest.spyOn(cookie, 'setCookie');
28
- });
29
-
30
- describe('getAccess', () => {
31
- beforeEach(() => {
32
- url.setCurrentHostname('www.avisnavn.no');
33
- jest
34
- .spyOn(jupiter, 'checkForAccess')
35
- .mockResolvedValue({ access: ['newspaper', 'plussalt'] });
36
- });
37
- it('returns list of access', async () => {
38
- expect(await getAccess()).toEqual({
39
- access: ['newspaper', 'plussalt'],
40
- });
41
- });
42
- });
43
-
44
- describe('activate', () => {
45
- describe('when all is ok', () => {
46
- beforeEach(() => {
47
- jest
48
- .spyOn(mercury, 'activateSubscription')
49
- .mockResolvedValue(['whatever']);
50
- });
51
- it('Returns whatever mercury returns', async () => {
52
- expect(await activate(['newspaper'], 'www.telen.no')).toEqual([
53
- 'whatever',
54
- ]);
55
- expect(mercury.activateSubscription).toHaveBeenCalledWith(
56
- ['newspaper'],
57
- 'www.telen.no'
58
- );
59
- });
60
- });
61
-
62
- describe('when user is deactivated', () => {
63
- beforeEach(() => {
64
- jest
65
- .spyOn(mercury, 'activateSubscription')
66
- .mockRejectedValue(new mercury.UserDeactivatedError());
67
- jest.spyOn(authentication, 'logout').mockResolvedValue(undefined);
68
- });
69
- it('Returns whatever mercury returns', async () => {
70
- expect(await activate([], 'www.telen.no')).toEqual([]);
71
- expect(mercury.activateSubscription).toHaveBeenCalledWith(
72
- [],
73
- 'www.telen.no'
74
- );
75
- expect(authentication.logout).toHaveBeenCalled();
76
- });
77
- });
78
- });
79
-
80
- describe('hasAccess', () => {
81
- let access = false;
82
- function itReturnsTrue() {
83
- it('returns true', () => {
84
- expect(access).toBeTruthy();
85
- });
86
- }
87
- function itReturnsFalse() {
88
- it('returns false', () => {
89
- expect(access).not.toBeTruthy();
90
- });
91
- }
92
- describe('with no access requested', () => {
93
- beforeEach(() => {
94
- access = hasAccess(['newspaper'], []);
95
- });
96
- itReturnsTrue();
97
- });
98
-
99
- describe('with access requested without access', () => {
100
- beforeEach(() => {
101
- access = hasAccess([], ['newspaper']);
102
- });
103
- itReturnsFalse();
104
- });
105
-
106
- describe('with access to some requested access feature', () => {
107
- beforeEach(() => {
108
- access = hasAccess(['newspaper'], ['all', 'plussalt', 'newspaper']);
109
- });
110
- itReturnsTrue();
111
- });
112
-
113
- describe('with access to other access features than requested requested access feature', () => {
114
- beforeEach(() => {
115
- access = hasAccess(['pluss', 'sport'], ['all', 'plussalt', 'newspaper']);
116
- });
117
- itReturnsFalse();
118
- });
119
- });
120
-
121
- let cookieResponse: any;
122
-
123
- function itReturnsCookieResponse(success: any, accessFeatures: AccessFeatures) {
124
- it(`returns cookie response with success = ${success}`, () => {
125
- expect(cookieResponse.success).toEqual(success);
126
- });
127
- it(`returns cookie response with accessFeatures = ${accessFeatures}`, () => {
128
- expect(cookieResponse.accessFeatures).toEqual(accessFeatures);
129
- });
130
- }
131
-
132
- function itSetsNoCookies() {
133
- it('does not set any cookies', () => {
134
- expect(cookie.setCookie).not.toHaveBeenCalled();
135
- });
136
- }
137
-
138
- function itDoesNotSetVstokenCookie() {
139
- it('does not set VSTOKEN cookie', () => {
140
- expect(cookie.setCookie).not.toHaveBeenCalledWith('VSTOKEN');
141
- });
142
- }
143
-
144
- function itSetsVstokenCookie() {
145
- it('sets VSTOKEN cookie', () => {
146
- expect(cookie.setCookie).toHaveBeenCalledWith(
147
- 'VSTOKEN',
148
- 'COOKIE_VALUE',
149
- 365,
150
- '/'
151
- );
152
- });
153
- }
154
-
155
- function itDoesNotSetVstoken2Cookie() {
156
- it('does not set VSTOKEN2 cookie', () => {
157
- expect(cookie.setCookie).not.toHaveBeenCalledWith('VSTOKEN2');
158
- });
159
- }
160
-
161
- function itSetsVstoken2Cookie() {
162
- it('sets VSTOKEN2 cookie', () => {
163
- expect(cookie.setCookie).toHaveBeenCalledWith(
164
- 'VSTOKEN2',
165
- 'COOKIE2_VALUE',
166
- 1,
167
- '/'
168
- );
169
- });
170
- }
171
-
172
- function mockGetUserAccess(status: any, accessFeatures: AccessFeatures) {
173
- beforeEach(async () => {
174
- jest.spyOn(jupiter, 'getUserAccess').mockResolvedValue({
175
- status,
176
- cookie: 'COOKIE_VALUE',
177
- access_features: accessFeatures,
178
- });
179
- });
180
- }
181
-
182
- function getUserAccessSucceeds(accessFeatures: AccessFeatures) {
183
- mockGetUserAccess('success', accessFeatures);
184
- }
185
-
186
- function getUserAccessFails(accessFeatures: AccessFeatures) {
187
- mockGetUserAccess('failure', accessFeatures);
188
- }
189
-
190
- function mockGetNonUserAccessSucceeds(
191
- status: any,
192
- accessFeatures: AccessFeatures
193
- ) {
194
- beforeEach(async () => {
195
- jest.spyOn(jupiter, 'getNonUserAccess').mockResolvedValue({
196
- status,
197
- uuid: 'mycompany',
198
- vstoken_cookie: 'COOKIE2_VALUE',
199
- access_features: accessFeatures,
200
- });
201
- });
202
- }
203
-
204
- function getNonUserAccessSucceeds(accessFeatures: AccessFeatures) {
205
- mockGetNonUserAccessSucceeds('success', accessFeatures);
206
- }
207
-
208
- function getNonUserAccessFails(accessFeatures: AccessFeatures) {
209
- mockGetNonUserAccessSucceeds('failure', accessFeatures);
210
- }
211
-
212
- describe('setUserAccessCookie', () => {
213
- describe('when getUserAccess is successful', () => {
214
- getUserAccessSucceeds(['newspaper', 'plussalt']);
215
- beforeEach(async () => {
216
- cookieResponse = await setUserAccessCookie(siteDomain);
217
- });
218
- itReturnsCookieResponse(true, ['newspaper', 'plussalt']);
219
- itSetsVstokenCookie();
220
- });
221
-
222
- describe('when getUserAccess is not successful', () => {
223
- getUserAccessFails(['newspaper', 'plussalt']);
224
- beforeEach(async () => {
225
- cookieResponse = await setUserAccessCookie(siteDomain);
226
- });
227
- itReturnsCookieResponse(false, ['newspaper', 'plussalt']);
228
- itSetsNoCookies();
229
- });
230
- });
231
-
232
- describe('setNonUserAccessCookie', () => {
233
- describe('when getNonUserAccess is successful', () => {
234
- getNonUserAccessSucceeds(['newspaper', 'plussalt']);
235
- beforeEach(async () => {
236
- cookieResponse = await setNonUserAccessCookie(siteDomain);
237
- });
238
- itReturnsCookieResponse(true, ['newspaper', 'plussalt']);
239
- itSetsVstoken2Cookie();
240
- });
241
-
242
- describe('when getNonUserAccess is not successful', () => {
243
- getNonUserAccessFails(['newspaper', 'plussalt']);
244
- beforeEach(async () => {
245
- cookieResponse = await setNonUserAccessCookie(siteDomain);
246
- });
247
- itReturnsCookieResponse(false, ['newspaper', 'plussalt']);
248
- itSetsNoCookies();
249
- });
250
- });
251
-
252
- describe('setAccessCookies', () => {
253
- describe('when both VSTOKEN and VSTOKEN2 requests succeed', () => {
254
- getUserAccessSucceeds(['newspaper', 'plussalt']);
255
- getNonUserAccessSucceeds(['sport', 'pluss', 'newspaper']);
256
- beforeEach(async () => {
257
- cookieResponse = await setAccessCookies(siteDomain);
258
- });
259
- itReturnsCookieResponse(true, ['newspaper', 'pluss', 'plussalt', 'sport']);
260
- itSetsVstokenCookie();
261
- itSetsVstoken2Cookie();
262
- });
263
-
264
- describe('when VSTOKEN fails and VSTOKEN2 succeeds', () => {
265
- getUserAccessFails(['newspaper']);
266
- getNonUserAccessSucceeds(['sport', 'pluss', 'newspaper']);
267
- beforeEach(async () => {
268
- cookieResponse = await setAccessCookies(siteDomain);
269
- });
270
- itReturnsCookieResponse(false, ['newspaper', 'pluss', 'sport']);
271
- itDoesNotSetVstokenCookie();
272
- itSetsVstoken2Cookie();
273
- });
274
-
275
- describe('when VSTOKEN succeeds and VSTOKEN2 fails', () => {
276
- getUserAccessSucceeds(['newspaper', 'plussalt']);
277
- getNonUserAccessFails(['newspaper']);
278
- beforeEach(async () => {
279
- cookieResponse = await setAccessCookies(siteDomain);
280
- });
281
- itReturnsCookieResponse(false, ['newspaper', 'plussalt']);
282
- itSetsVstokenCookie();
283
- itDoesNotSetVstoken2Cookie();
284
- });
285
-
286
- describe('when both VSTOKEN and VSTOKEN2 fails', () => {
287
- getUserAccessFails(['newspaper', 'plussalt']);
288
- getNonUserAccessFails(['newspaper']);
289
- beforeEach(async () => {
290
- cookieResponse = await setAccessCookies(siteDomain);
291
- });
292
- itReturnsCookieResponse(false, ['newspaper', 'plussalt']);
293
- itSetsNoCookies();
294
- });
295
- });
296
-
297
- describe('reload loop protection', () => {
298
- const currentUrl = 'http://www.avisnavn.no/myAwesomeArticle';
299
- const otherUrl = 'https://www.avisnavn.no/someBoringArticle';
300
-
301
- beforeEach(() => {
302
- jest.spyOn(url, 'getCurrentUrl').mockReturnValue(currentUrl);
303
- });
304
-
305
- describe('setHasPerformedPaywallReload', () => {
306
- describe('without requestedUrl', () => {
307
- beforeEach(() => {
308
- setHasPerformedPaywallReload();
309
- });
310
- it('sets aid-paywall-reload-performed with current URL as value', () => {
311
- const twoMinutesFromNow = new Date().getTime() + 2 * 60 * 1000;
312
- expect(cookie.setCookie).toHaveBeenCalledWith(
313
- 'aid-paywall-reload-performed',
314
- currentUrl,
315
- expect.toBeWithin(twoMinutesFromNow - 5000, twoMinutesFromNow + 5000)
316
- );
317
- });
318
- });
319
- describe('with requestedUrl', () => {
320
- beforeEach(() => {
321
- setHasPerformedPaywallReload(otherUrl);
322
- });
323
- it('sets aid-paywall-reload-performed with current URL as value', () => {
324
- const twoMinutesFromNow = new Date().getTime() + 2 * 60 * 1000;
325
- expect(cookie.setCookie).toHaveBeenCalledWith(
326
- 'aid-paywall-reload-performed',
327
- otherUrl,
328
- expect.toBeWithin(twoMinutesFromNow - 5000, twoMinutesFromNow + 5000)
329
- );
330
- });
331
- });
332
- });
333
-
334
- describe('hasRecentlyPerformedPaywallReload', () => {
335
- function itReturnsTrue() {
336
- it('returns true', () => {
337
- expect(hasRecentlyPerformedPaywallReload()).toBeTruthy();
338
- });
339
- }
340
- function itReturnsFalse() {
341
- it('returns false', () => {
342
- expect(hasRecentlyPerformedPaywallReload()).toBeFalsy();
343
- });
344
- }
345
- describe('when has recently tried to unlock paywall on same URL', () => {
346
- beforeEach(() => {
347
- setHasPerformedPaywallReload();
348
- });
349
- itReturnsTrue();
350
- });
351
- describe('when has recently tried to unlock paywall on different URL', () => {
352
- beforeEach(() => {
353
- jest
354
- .spyOn(url, 'getCurrentUrl')
355
- .mockReturnValueOnce(otherUrl)
356
- .mockReturnValue(currentUrl);
357
- setHasPerformedPaywallReload();
358
- });
359
- itReturnsFalse();
360
- });
361
- describe('when has recently tried to unlock paywall on different URL, and this URL is specified', () => {
362
- beforeEach(() => {
363
- jest
364
- .spyOn(url, 'getCurrentUrl')
365
- .mockReturnValueOnce(otherUrl) // This will be the value in our cookie
366
- .mockReturnValue(currentUrl);
367
- setHasPerformedPaywallReload();
368
- });
369
- it('returns true', () => {
370
- expect(hasRecentlyPerformedPaywallReload(otherUrl)).toBeTruthy();
371
- });
372
- });
373
- describe('when aid-paywall-reload-performed is not present', () => {
374
- itReturnsFalse();
375
- });
376
- });
377
- });
@@ -1,120 +0,0 @@
1
- import {
2
- checkForAccess,
3
- getNonUserAccess,
4
- getUserAccess,
5
- } from '../clients/jupiter';
6
- import { getCurrentSiteDomain, getCurrentUrl } from '../utils/url';
7
- import { UserAttributes } from '../types';
8
- import { activateSubscription, UserDeactivatedError } from '../clients/mercury';
9
- import { logout } from './authentication';
10
- import { getCookie, setCookie } from '../lib/cookie';
11
-
12
- type SetCookieResponse = { success: boolean; accessFeatures: string[] };
13
-
14
- export const getAccess = (
15
- accessFeatures: string[] = ['newspaper']
16
- ): Promise<Pick<UserAttributes, 'access'>> =>
17
- checkForAccess(getCurrentSiteDomain(), accessFeatures);
18
-
19
- export const activate = async (
20
- accessFeatures: string[],
21
- siteDomain: string
22
- ): Promise<string[]> => {
23
- try {
24
- return await activateSubscription(accessFeatures, siteDomain);
25
- } catch (error) {
26
- if (error instanceof UserDeactivatedError) {
27
- await logout();
28
- return [];
29
- }
30
- throw error;
31
- }
32
- };
33
-
34
- export const hasAccess = (
35
- currentAccessFeatures: string[],
36
- requestedAccessFeatures: string[]
37
- ): boolean =>
38
- requestedAccessFeatures.length < 1 ||
39
- requestedAccessFeatures.filter((requestedAccessFeature) =>
40
- currentAccessFeatures.includes(requestedAccessFeature)
41
- ).length > 0;
42
-
43
- export const setUserAccessCookie = async (
44
- siteDomain: string
45
- ): Promise<SetCookieResponse> => {
46
- const vstoken = await getUserAccess(siteDomain);
47
- if (vstoken.status === 'success') {
48
- /**
49
- * The VSTOKEN cookie will live for 365 days, but a timestamp in the payload will ensure that it cannot
50
- * be used to gain access for that long. The reason we want the cookie to live long is that it's also
51
- * used to keep subscribers from seeing ads for buying the subscription they already have.
52
- */
53
- setCookie('VSTOKEN', vstoken.cookie, 365, '/');
54
- }
55
- return {
56
- success: vstoken.status === 'success',
57
- accessFeatures: vstoken.access_features,
58
- };
59
- };
60
-
61
- export const setNonUserAccessCookie = async (
62
- siteDomain: string
63
- ): Promise<SetCookieResponse> => {
64
- const vstoken2 = await getNonUserAccess(siteDomain);
65
- if (vstoken2.status === 'success') {
66
- setCookie('VSTOKEN2', vstoken2.vstoken_cookie, 1, '/');
67
- }
68
- return {
69
- success: vstoken2.status === 'success',
70
- accessFeatures: vstoken2.access_features,
71
- };
72
- };
73
-
74
- export const setAccessCookies = async (
75
- siteDomain: string
76
- ): Promise<SetCookieResponse> => {
77
- const setters: Array<Promise<SetCookieResponse>> = [];
78
- setters.push(
79
- setUserAccessCookie(siteDomain).catch(() =>
80
- Promise.resolve({ success: false, accessFeatures: [] })
81
- )
82
- );
83
- setters.push(
84
- setNonUserAccessCookie(siteDomain).catch(() =>
85
- Promise.resolve({ success: false, accessFeatures: [] })
86
- )
87
- );
88
- return Promise.all(setters).then((results) =>
89
- results.reduce(
90
- (accumulatedResult, result) => ({
91
- success: accumulatedResult.success && result.success,
92
- accessFeatures: accumulatedResult.accessFeatures
93
- .concat(result.accessFeatures)
94
- .filter((v, i, a) => a.indexOf(v) === i) // Remove duplicates by keeping only first copy
95
- .sort(), // We want to keep result deterministic for easy testing
96
- }),
97
- {
98
- success: true,
99
- accessFeatures: [],
100
- }
101
- )
102
- );
103
- };
104
-
105
- export const setHasPerformedPaywallReload = (requestedUrl?: string): void => {
106
- const expires = new Date();
107
- expires.setTime(expires.getTime() + 2 * 60 * 1000); // Add two minutes
108
-
109
- setCookie(
110
- 'aid-paywall-reload-performed',
111
- requestedUrl || getCurrentUrl(),
112
- expires
113
- );
114
- };
115
-
116
- export const hasRecentlyPerformedPaywallReload = (
117
- requestedUrl?: string
118
- ): boolean =>
119
- getCookie('aid-paywall-reload-performed') ===
120
- (requestedUrl || getCurrentUrl());
@@ -1,41 +0,0 @@
1
- import fetch from 'jest-fetch-mock';
2
- import cache from '../cache';
3
- import { getPrivacyPreferences } from './preferences';
4
-
5
- beforeEach(async () => {
6
- await cache.clear();
7
- });
8
-
9
- const europaResponse = {
10
- namespaces: {
11
- privacy_preferences: {
12
- allow_research_usage: 'true',
13
- connect_with_surveys: true,
14
- personalized_ads: 'false',
15
- personalized_content: false,
16
- },
17
- },
18
- };
19
-
20
- describe('privacyPreferences', () => {
21
- it('should return preferences', async () => {
22
- fetch.mockResponse(JSON.stringify(europaResponse));
23
- await getPrivacyPreferences();
24
- expect(fetch).toHaveBeenCalledTimes(1);
25
- });
26
-
27
- it('should use cache if available', async () => {
28
- fetch.mockResponse(JSON.stringify(europaResponse));
29
-
30
- jest.spyOn(cache, 'get').mockReturnValue(
31
- Promise.resolve({
32
- allowResearchUsage: true,
33
- connectWithSurveys: true,
34
- personalizedAds: false,
35
- personalizedContent: false,
36
- })
37
- );
38
- await Promise.all([getPrivacyPreferences(), getPrivacyPreferences()]);
39
- expect(fetch).toHaveBeenCalledTimes(0);
40
- });
41
- });
@@ -1,41 +0,0 @@
1
- import { Record, Boolean } from 'runtypes';
2
- import { getNamespaces } from '../clients/europa';
3
- import { UserAttributes } from '../types';
4
- import getOrUpdate from '../utils/getOrUpdate';
5
-
6
- const CACHE_DURATION = 5 * 60000; // 5 minutes
7
- const PRIVACY_PREFERENCES_CACHE_KEY = 'privacyPreferences';
8
-
9
- export const PrivacyPreferencesSchema = Record({
10
- allowResearchUsage: Boolean,
11
- connectWithSurveys: Boolean,
12
- personalizedAds: Boolean,
13
- personalizedContent: Boolean,
14
- });
15
-
16
- const toBoolean = (val: string | boolean) => val === 'true' || val === true;
17
-
18
- export const getPrivacyPreferences = async (): Promise<
19
- Pick<UserAttributes, 'privacyPreferences'>
20
- > =>
21
- getOrUpdate(PRIVACY_PREFERENCES_CACHE_KEY, PrivacyPreferencesSchema, () =>
22
- getNamespaces(['privacy_preferences']).then((namespaces) => {
23
- const privacyPreferences: any = namespaces.privacy_preferences;
24
-
25
- return {
26
- ttl: CACHE_DURATION,
27
- data: {
28
- allowResearchUsage: toBoolean(
29
- privacyPreferences.allow_research_usage
30
- ),
31
- connectWithSurveys: toBoolean(
32
- privacyPreferences.connect_with_surveys
33
- ),
34
- personalizedAds: toBoolean(privacyPreferences.personalized_ads),
35
- personalizedContent: toBoolean(
36
- privacyPreferences.personalized_content
37
- ),
38
- },
39
- };
40
- })
41
- ).then((data) => ({ privacyPreferences: data }));