@amedia/user 0.13.39 → 0.13.41

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 (86) hide show
  1. package/dist/user.cjs +1 -1
  2. package/dist/user.cjs.map +3 -3
  3. package/dist/user.d.ts +5 -5
  4. package/dist/user.js +1 -1
  5. package/dist/user.js.map +3 -3
  6. package/package.json +5 -3
  7. package/src/actions/authentication.spec.ts +51 -0
  8. package/src/actions/authentication.ts +43 -0
  9. package/src/actions/authorization.spec.ts +369 -0
  10. package/src/actions/authorization.ts +117 -0
  11. package/src/actions/preferences.spec.ts +41 -0
  12. package/src/actions/preferences.ts +41 -0
  13. package/src/actions/storage.ts +22 -0
  14. package/src/actions/userData.spec.ts +133 -0
  15. package/src/actions/userData.ts +68 -0
  16. package/src/autologin/index.spec.ts +239 -0
  17. package/src/autologin/index.ts +92 -0
  18. package/src/autologin/thirdPartyCookie.spec.ts +95 -0
  19. package/src/autologin/thirdPartyCookie.ts +55 -0
  20. package/src/cache/engines/global.spec.ts +62 -0
  21. package/src/cache/engines/global.ts +49 -0
  22. package/src/cache/index.spec.ts +130 -0
  23. package/src/cache/index.ts +48 -0
  24. package/src/cache/types.ts +12 -0
  25. package/src/clients/europa.spec.ts +209 -0
  26. package/src/clients/europa.ts +183 -0
  27. package/src/clients/jupiter.spec.ts +179 -0
  28. package/src/clients/jupiter.ts +119 -0
  29. package/src/clients/mercury.spec.ts +59 -0
  30. package/src/clients/mercury.ts +48 -0
  31. package/src/clients/mercuryLog.spec.ts +20 -0
  32. package/src/clients/mercuryLog.ts +67 -0
  33. package/src/clients/nebula.spec.ts +70 -0
  34. package/src/clients/nebula.ts +83 -0
  35. package/src/clients/pluto.spec.ts +165 -0
  36. package/src/clients/pluto.ts +118 -0
  37. package/src/eventHandlers/activation.ts +36 -0
  38. package/src/eventHandlers/authentication.ts +34 -0
  39. package/src/eventHandlers/eventMap.ts +34 -0
  40. package/src/eventHandlers/state.spec.ts +48 -0
  41. package/src/eventHandlers/state.ts +23 -0
  42. package/src/eventHandlers/storage.spec.ts +114 -0
  43. package/src/eventHandlers/storage.ts +45 -0
  44. package/src/eventHandlers/userAttributes.spec.ts +93 -0
  45. package/src/eventHandlers/userAttributes.ts +31 -0
  46. package/src/exceptions/FetchTimeoutError.ts +8 -0
  47. package/src/exceptions/PaywallError.ts +16 -0
  48. package/src/index-authentcation.spec.ts +26 -0
  49. package/src/index-storage.spec.ts +144 -0
  50. package/src/index-subscription.spec.ts +213 -0
  51. package/src/index.ts +40 -0
  52. package/src/janitor/index.spec.ts +18 -0
  53. package/src/janitor/index.ts +59 -0
  54. package/src/janitor/jobs/accessCookieRefresher.spec.ts +213 -0
  55. package/src/janitor/jobs/accessCookieRefresher.ts +98 -0
  56. package/src/janitor/jobs/daxsubCookie.spec.ts +109 -0
  57. package/src/janitor/jobs/daxsubCookie.ts +38 -0
  58. package/src/janitor/jobs/removeUserStorage.spec.ts +34 -0
  59. package/src/janitor/jobs/removeUserStorage.ts +12 -0
  60. package/src/lib/PaywallUnlockRequest.spec.ts +363 -0
  61. package/src/lib/PaywallUnlockRequest.ts +143 -0
  62. package/src/lib/UserDataRequest.spec.ts +231 -0
  63. package/src/lib/UserDataRequest.ts +267 -0
  64. package/src/lib/cookie.ts +121 -0
  65. package/src/lib/rpc.ts +19 -0
  66. package/src/store/index.spec.ts +49 -0
  67. package/src/store/index.ts +64 -0
  68. package/src/types.ts +22 -0
  69. package/src/utils/customEventWrapper.ts +58 -0
  70. package/src/utils/debouncer.spec.ts +252 -0
  71. package/src/utils/debouncer.ts +123 -0
  72. package/src/utils/deepEquals.ts +42 -0
  73. package/src/utils/expectBootLogs.ts +9 -0
  74. package/src/utils/getGlobalThis.ts +17 -0
  75. package/src/utils/getOrUpdate.spec.ts +166 -0
  76. package/src/utils/getOrUpdate.ts +66 -0
  77. package/src/utils/localhostCheck.ts +10 -0
  78. package/src/utils/location.ts +31 -0
  79. package/src/utils/log.spec.ts +148 -0
  80. package/src/utils/log.ts +124 -0
  81. package/src/utils/loginState.ts +24 -0
  82. package/src/utils/networkError.ts +11 -0
  83. package/src/utils/queue.ts +32 -0
  84. package/src/utils/type.ts +19 -0
  85. package/src/utils/url.spec.ts +33 -0
  86. package/src/utils/url.ts +37 -0
@@ -0,0 +1,22 @@
1
+ import {
2
+ getNamespaces,
3
+ saveNamespace,
4
+ updateNamespace,
5
+ } from '../clients/europa';
6
+ import store from '../store';
7
+
8
+ export const requestStorage = (namespaces: string[]) => {
9
+ getNamespaces(namespaces).then((storage) => {
10
+ store.merge('storage', storage);
11
+ });
12
+ };
13
+
14
+ export const updateStorage = (storage: { [namespace: string]: object }) =>
15
+ Object.keys(storage).forEach((namespace) =>
16
+ updateNamespace(namespace, storage[namespace])
17
+ );
18
+
19
+ export const saveStorage = (storage: { [namespace: string]: object }) =>
20
+ Object.keys(storage).forEach((namespace) =>
21
+ saveNamespace(namespace, storage[namespace])
22
+ );
@@ -0,0 +1,133 @@
1
+ import fetch, { FetchMock } from 'jest-fetch-mock';
2
+ import cache from '../cache';
3
+ import store from '../store';
4
+ import { requestAttributes } from './userData';
5
+ import * as preferences from './preferences';
6
+ import * as nebula from '../clients/nebula';
7
+ import * as pluto from '../clients/pluto';
8
+ import useRealTimers = jest.useRealTimers;
9
+ import useFakeTimers = jest.useFakeTimers;
10
+
11
+ describe('when fetching userData', () => {
12
+ let plutoFetchMock: FetchMock;
13
+ beforeEach(() => {
14
+ plutoFetchMock = fetch.doMockIf('/api/pluto/v1/sessions/current');
15
+ cache.clear();
16
+ store.clear();
17
+ });
18
+
19
+ describe('when querying multiple attributes', () => {
20
+ describe('from a single source', () => {
21
+ beforeEach(async () => {
22
+ plutoFetchMock.mockOnce(
23
+ JSON.stringify({
24
+ user_uuid: '1234-123-1234',
25
+ user_name: 'Donald',
26
+ tracking_key: '4321-321-4321',
27
+ })
28
+ );
29
+ await requestAttributes(['name', 'uuid']);
30
+ });
31
+
32
+ it('should ask only once', () => {
33
+ expect(plutoFetchMock).toHaveBeenCalledTimes(1);
34
+ });
35
+
36
+ it('should have expected data in store', () => {
37
+ expect(store.get('userAttributes')).toEqual({
38
+ uuid: '1234-123-1234',
39
+ name: 'Donald',
40
+ trackingKey: '4321-321-4321',
41
+ });
42
+ });
43
+ });
44
+
45
+ describe('in quick succession', () => {
46
+ beforeEach(async () => {
47
+ plutoFetchMock.mockResponse(
48
+ JSON.stringify({
49
+ user_uuid: '1234-123-1234',
50
+ user_name: 'Donald',
51
+ tracking_key: '4321-321-4321',
52
+ })
53
+ );
54
+ await Promise.all([
55
+ requestAttributes(['name', 'uuid']),
56
+ requestAttributes(['uuid']),
57
+ requestAttributes(['name']),
58
+ requestAttributes(['name', 'uuid']),
59
+ requestAttributes(['uuid', 'name']),
60
+ ]);
61
+ });
62
+
63
+ it('should ask only once', () => {
64
+ expect(plutoFetchMock).toHaveBeenCalledTimes(1);
65
+ });
66
+
67
+ it('should have expected data in store', () => {
68
+ expect(store.get('userAttributes')).toEqual({
69
+ uuid: '1234-123-1234',
70
+ name: 'Donald',
71
+ trackingKey: '4321-321-4321',
72
+ });
73
+ });
74
+ });
75
+ });
76
+
77
+ describe('when querying for attributes that need login state to be resolved', () => {
78
+ beforeEach(() => {
79
+ useFakeTimers();
80
+ jest.spyOn(pluto, 'getCurrentSession').mockResolvedValue({});
81
+ spyOn(preferences, 'getPrivacyPreferences').and.returnValue(
82
+ Promise.resolve({})
83
+ );
84
+ spyOn(nebula, 'getInfo').and.returnValue(Promise.resolve({}));
85
+
86
+ requestAttributes(['uuid', 'extraData', 'privacyPreferences']);
87
+
88
+ expect(pluto.getCurrentSession).toHaveBeenCalled();
89
+ expect(preferences.getPrivacyPreferences).not.toHaveBeenCalled();
90
+ expect(nebula.getInfo).not.toHaveBeenCalled();
91
+ });
92
+
93
+ afterEach(() => {
94
+ useRealTimers();
95
+ });
96
+
97
+ describe('when resolves to logged in', () => {
98
+ beforeEach(() => {
99
+ store.set('state', { isLoggedIn: true });
100
+ });
101
+
102
+ it('should have called pluto', () => {
103
+ expect(pluto.getCurrentSession).toHaveBeenCalled();
104
+ });
105
+
106
+ it('should have called preferences', () => {
107
+ expect(preferences.getPrivacyPreferences).toHaveBeenCalled();
108
+ });
109
+
110
+ it('should have called nebula', () => {
111
+ expect(nebula.getInfo).toHaveBeenCalled();
112
+ });
113
+ });
114
+
115
+ describe('when resolves to guest', () => {
116
+ beforeEach(() => {
117
+ store.set('state', { isLoggedIn: false });
118
+ });
119
+
120
+ it('should have called pluto', () => {
121
+ expect(pluto.getCurrentSession).toHaveBeenCalled();
122
+ });
123
+
124
+ it('should not have called preferences', () => {
125
+ expect(preferences.getPrivacyPreferences).not.toHaveBeenCalled();
126
+ });
127
+
128
+ it('should have called nebula', () => {
129
+ expect(nebula.getInfo).toHaveBeenCalled();
130
+ });
131
+ });
132
+ });
133
+ });
@@ -0,0 +1,68 @@
1
+ import { getBrowserId } from '@amedia/browserid';
2
+ import log from '../utils/log';
3
+ import { UserAttributes } from '../types';
4
+ import { getSession } from './authentication';
5
+ import { getAccess } from './authorization';
6
+ import { getPrivacyPreferences } from './preferences';
7
+ import store from '../store';
8
+ import { getInfo } from '../clients/nebula';
9
+ import { whenIsLoggedIn, whenLoginStateResolved } from '../utils/loginState';
10
+ import { getCurrentPublicationDomain } from '../utils/url';
11
+
12
+ const getExtraData = () =>
13
+ Promise.all([getBrowserId(), whenLoginStateResolved()]).then(
14
+ ([browserId, isLoggedIn]) =>
15
+ getInfo(
16
+ getCurrentPublicationDomain(),
17
+ browserId,
18
+ isLoggedIn
19
+ ? store.get('userAttributes')?.trackingKey || undefined
20
+ : undefined
21
+ )
22
+ );
23
+
24
+ const dataServiceMap: {
25
+ [key in keyof UserAttributes]?: () => Promise<Partial<UserAttributes>>;
26
+ } = {
27
+ uuid: getSession,
28
+ name: getSession,
29
+ trackingKey: getSession,
30
+ access: () => whenIsLoggedIn().then(() => getAccess()),
31
+ extraData: getExtraData,
32
+ privacyPreferences: () =>
33
+ whenIsLoggedIn().then(() => getPrivacyPreferences()),
34
+ };
35
+
36
+ export const requestAttributes = (attributes: Array<keyof UserAttributes>) => {
37
+ const requiredServices: Array<() => Promise<UserAttributes>> = [];
38
+ attributes.forEach((attribute) => {
39
+ const service = dataServiceMap[attribute];
40
+ if (!service) {
41
+ log.warn(`Unknown attribute ${attribute} was requested`);
42
+ return;
43
+ }
44
+ if (!requiredServices.includes(service)) {
45
+ requiredServices.push(service);
46
+ }
47
+ });
48
+
49
+ const promises: Promise<void>[] = [];
50
+ requiredServices.forEach((service) => {
51
+ promises.push(
52
+ service()
53
+ .then((data) => {
54
+ store.merge('userAttributes', data);
55
+ if (data.uuid !== undefined) {
56
+ // We have tried to fetch uuid, so we now know if the user is logged in or not
57
+ store.merge('state', {
58
+ isLoggedIn: data.uuid !== null,
59
+ });
60
+ }
61
+ })
62
+ .catch((error) => {
63
+ log.warn(`User attribute call failed (${service.toString()})`, error);
64
+ })
65
+ );
66
+ });
67
+ return Promise.all(promises).then(() => {});
68
+ };
@@ -0,0 +1,239 @@
1
+ import store from '../store';
2
+ import * as thirdPartyCookie from './thirdPartyCookie';
3
+ import {
4
+ attemptAutoLoginJob,
5
+ attemptPaywallAutoLogin,
6
+ AUTOLOGIN_COOKIE_TTL,
7
+ } from './index';
8
+ import * as location from '../utils/location';
9
+ import * as url from '../utils/url';
10
+ import * as cookie from '../lib/cookie';
11
+ import UserDataRequest from '../lib/UserDataRequest';
12
+
13
+ function itShouldNotNavigateAway() {
14
+ it('should not navigate away', () => {
15
+ expect(location.navigateTo).not.toHaveBeenCalled();
16
+ });
17
+ }
18
+
19
+ function itShouldCallThirdPartyCookieStrategy() {
20
+ it('should try third party auto login', () => {
21
+ expect(thirdPartyCookie.default).toHaveBeenCalledTimes(1);
22
+ });
23
+ }
24
+
25
+ function itShouldNavigateToAutoLogin(context: string) {
26
+ it(`should navigate to auto with context ${context}`, async () => {
27
+ expect(location.navigateTo).toHaveBeenCalledWith(
28
+ `https://www.aid.no/aid/logg_inn/auto?context=auto_login_${context}&requestedUrl=https%3A%2F%2Fwww.avisnavn.no%2Fabo%2F%3Fquery%3Dparam`
29
+ );
30
+ });
31
+ }
32
+
33
+ let getCookieSpy: jasmine.Spy;
34
+
35
+ beforeEach(() => {
36
+ jest.mock('./thirdPartyCookie');
37
+ spyOn(location, 'navigateTo');
38
+ spyOn(url, 'getAidDomain').and.returnValue('www.aid.no');
39
+ spyOn(url, 'getCurrentUrl').and.returnValue(
40
+ 'https://www.avisnavn.no/abo/?query=param'
41
+ );
42
+ getCookieSpy = spyOn(cookie, 'getCookie').and.returnValue('0');
43
+ spyOn(cookie, 'setCookie');
44
+ });
45
+
46
+ describe('attemptAutoLoginJob', () => {
47
+ let shouldPerformAutoLogin = false;
48
+
49
+ beforeEach(() => {
50
+ shouldPerformAutoLogin = false;
51
+ jest
52
+ .spyOn(thirdPartyCookie, 'default')
53
+ .mockImplementation(() => Promise.resolve(shouldPerformAutoLogin));
54
+ });
55
+
56
+ describe('when already logged in', () => {
57
+ beforeEach(async () => {
58
+ jest
59
+ .spyOn(UserDataRequest.prototype, 'subscribe')
60
+ .mockImplementation((callback) => {
61
+ callback({
62
+ attributes: {
63
+ name: 'Some name',
64
+ },
65
+ state: {
66
+ isLoggedIn: true,
67
+ },
68
+ });
69
+ });
70
+ store.set('state', { isLoggedIn: true });
71
+ await attemptAutoLoginJob();
72
+ });
73
+
74
+ it('should not try third party auto login', () => {
75
+ expect(thirdPartyCookie.default).not.toHaveBeenCalled();
76
+ });
77
+ });
78
+
79
+ describe('when not already logged in', () => {
80
+ beforeEach(async () => {
81
+ jest
82
+ .spyOn(UserDataRequest.prototype, 'subscribe')
83
+ .mockImplementation((callback) => {
84
+ callback({
85
+ attributes: {},
86
+ state: {
87
+ isLoggedIn: false,
88
+ },
89
+ });
90
+ });
91
+ store.set('state', { isLoggedIn: false });
92
+ });
93
+
94
+ describe('when in iframe (Dr. Edition)', () => {
95
+ let originalTop: Window;
96
+ beforeEach(async () => {
97
+ originalTop = global.top;
98
+ // @ts-ignore
99
+ delete global.top; // Set window.top to something other than window.self
100
+ // @ts-ignore
101
+ global.top = {};
102
+ await attemptAutoLoginJob();
103
+ });
104
+ afterEach(() => {
105
+ // @ts-ignore
106
+ global.top = originalTop;
107
+ });
108
+
109
+ itShouldNotNavigateAway();
110
+ });
111
+
112
+ describe('when a strategy triggers auto login', () => {
113
+ beforeEach(async () => {
114
+ shouldPerformAutoLogin = true;
115
+ await attemptAutoLoginJob();
116
+ });
117
+
118
+ itShouldCallThirdPartyCookieStrategy();
119
+ itShouldNavigateToAutoLogin('third_party');
120
+ });
121
+ describe('when no strategy triggers auto login', () => {
122
+ beforeEach(async () => {
123
+ await attemptAutoLoginJob();
124
+ });
125
+
126
+ itShouldCallThirdPartyCookieStrategy();
127
+ itShouldNotNavigateAway();
128
+ });
129
+
130
+ describe('when already tried auto login', () => {
131
+ describe('when tried within the last minute', () => {
132
+ beforeEach(async () => {
133
+ getCookieSpy.and.returnValue(Date.now());
134
+ await attemptAutoLoginJob();
135
+ });
136
+ itShouldCallThirdPartyCookieStrategy();
137
+ itShouldNotNavigateAway();
138
+ });
139
+
140
+ describe('when last attempt is old', () => {
141
+ beforeEach(async () => {
142
+ getCookieSpy.and.returnValue(
143
+ Date.now() - AUTOLOGIN_COOKIE_TTL - 1000
144
+ );
145
+ await attemptAutoLoginJob();
146
+ });
147
+ itShouldCallThirdPartyCookieStrategy();
148
+ itShouldNotNavigateAway();
149
+ });
150
+ });
151
+ });
152
+ });
153
+
154
+ describe('attemptPaywallAutoLogin', () => {
155
+ beforeEach(() => {});
156
+
157
+ describe('when already logged in', () => {
158
+ beforeEach(async () => {
159
+ jest
160
+ .spyOn(UserDataRequest.prototype, 'subscribe')
161
+ .mockImplementation((callback) => {
162
+ callback({
163
+ attributes: {
164
+ name: 'Some name',
165
+ },
166
+ state: {
167
+ isLoggedIn: true,
168
+ },
169
+ });
170
+ });
171
+ store.set('state', { isLoggedIn: true });
172
+ await attemptPaywallAutoLogin();
173
+ });
174
+ });
175
+
176
+ describe('when not already logged in', () => {
177
+ beforeEach(async () => {
178
+ jest
179
+ .spyOn(UserDataRequest.prototype, 'subscribe')
180
+ .mockImplementation((callback) => {
181
+ callback({
182
+ attributes: {},
183
+ state: {
184
+ isLoggedIn: false,
185
+ },
186
+ });
187
+ });
188
+ store.set('state', { isLoggedIn: false });
189
+ });
190
+
191
+ describe('when in iframe (Dr. Edition)', () => {
192
+ let originalTop: Window;
193
+ beforeEach(async () => {
194
+ originalTop = global.top;
195
+ // @ts-ignore
196
+ delete global.top; // Set window.top to something other than window.self
197
+ // @ts-ignore
198
+ global.top = {};
199
+ await attemptPaywallAutoLogin();
200
+ });
201
+ afterEach(() => {
202
+ // @ts-ignore
203
+ global.top = originalTop;
204
+ });
205
+
206
+ itShouldNotNavigateAway();
207
+ });
208
+
209
+ describe('when not in iframe', () => {
210
+ describe('when already tried cookie is not found', () => {
211
+ beforeEach(async () => {
212
+ getCookieSpy.and.returnValue(undefined);
213
+ await attemptPaywallAutoLogin();
214
+ });
215
+ itShouldNavigateToAutoLogin('paywall');
216
+ });
217
+
218
+ describe('when already tried cookie was found', () => {
219
+ describe('when tried within the last minute', () => {
220
+ beforeEach(async () => {
221
+ getCookieSpy.and.returnValue(Date.now());
222
+ await attemptPaywallAutoLogin();
223
+ });
224
+ itShouldNotNavigateAway();
225
+ });
226
+
227
+ describe('when last attempt is old', () => {
228
+ beforeEach(async () => {
229
+ getCookieSpy.and.returnValue(
230
+ Date.now() - AUTOLOGIN_COOKIE_TTL - 1000
231
+ );
232
+ await attemptPaywallAutoLogin();
233
+ });
234
+ itShouldNavigateToAutoLogin('paywall');
235
+ });
236
+ });
237
+ });
238
+ });
239
+ });
@@ -0,0 +1,92 @@
1
+ import thirdPartyCookie from './thirdPartyCookie';
2
+ import { getAidDomain, getCurrentUrl } from '../utils/url';
3
+ import { navigateTo } from '../utils/location';
4
+ import { getCookie, removeCookie, setCookie } from '../lib/cookie';
5
+ import UserDataRequest from '../lib/UserDataRequest';
6
+
7
+ export type Strategies = Array<{
8
+ name: string;
9
+ handler: () => Promise<boolean>;
10
+ }>;
11
+
12
+ const AUTOLOGIN_COOKIE = 'has-tried-autologin';
13
+ export const AUTOLOGIN_COOKIE_TTL = 60000; // One minute
14
+
15
+ function inIframe() {
16
+ try {
17
+ return window.self !== window.top;
18
+ } catch (e) {
19
+ return true;
20
+ }
21
+ }
22
+
23
+ function hasAlreadyAttemptedAutoLogin() {
24
+ const cookie = getCookie(AUTOLOGIN_COOKIE);
25
+ if (cookie && typeof cookie !== 'object') {
26
+ try {
27
+ if (Date.now() - parseInt(cookie, 10) < AUTOLOGIN_COOKIE_TTL) {
28
+ return true;
29
+ }
30
+ } catch (e) {
31
+ removeCookie(AUTOLOGIN_COOKIE);
32
+ }
33
+ }
34
+ setCookie(AUTOLOGIN_COOKIE, Date.now(), Date.now() + AUTOLOGIN_COOKIE_TTL);
35
+ return false;
36
+ }
37
+
38
+ const attemptAutologin = async (strategies: Strategies) => {
39
+ if (typeof window === 'undefined' || inIframe()) {
40
+ // Avoid auto-login on preview for dr edition and in workers.
41
+ return;
42
+ }
43
+
44
+ const {
45
+ state: { isLoggedIn },
46
+ } = await new UserDataRequest().fetch();
47
+ if (isLoggedIn) {
48
+ return;
49
+ }
50
+
51
+ // eslint-disable-next-line no-restricted-syntax
52
+ for (const strategy of strategies) {
53
+ // eslint-disable-next-line no-await-in-loop
54
+ const shouldTryMoreStrategies = await strategy
55
+ .handler()
56
+ .then((shouldPerformAutoLogin) => {
57
+ if (shouldPerformAutoLogin) {
58
+ if (hasAlreadyAttemptedAutoLogin()) {
59
+ return false;
60
+ }
61
+
62
+ // Try to get newspaper cookie
63
+ const url = new URL(`https://${getAidDomain()}/aid/logg_inn/auto`);
64
+ url.searchParams.set('context', `auto_login_${strategy.name}`);
65
+ url.searchParams.set('requestedUrl', getCurrentUrl());
66
+ navigateTo(url.href);
67
+ return false;
68
+ }
69
+ return true;
70
+ });
71
+
72
+ if (!shouldTryMoreStrategies) {
73
+ return;
74
+ }
75
+ }
76
+ };
77
+
78
+ export const attemptAutoLoginJob = async () =>
79
+ attemptAutologin([
80
+ {
81
+ name: 'third_party',
82
+ handler: thirdPartyCookie,
83
+ },
84
+ ]);
85
+
86
+ export const attemptPaywallAutoLogin = async () =>
87
+ attemptAutologin([
88
+ {
89
+ name: 'paywall',
90
+ handler: () => Promise.resolve(true),
91
+ },
92
+ ]);
@@ -0,0 +1,95 @@
1
+ import fetch from 'jest-fetch-mock';
2
+ import cache from '../cache';
3
+ import thirdPartyCookie, { CACHE_KEY, CACHE_TTL } from './thirdPartyCookie';
4
+ import * as location from '../utils/location';
5
+ import * as url from '../utils/url';
6
+
7
+ let shouldRedirectToAutoLogin = false;
8
+
9
+ function itShouldSetAlreadyTriedCache() {
10
+ it('should set already tried cache', () => {
11
+ expect(cache.set).toHaveBeenCalledWith(CACHE_KEY, true, CACHE_TTL);
12
+ });
13
+ }
14
+
15
+ function itShouldRedirectToAutoLogin() {
16
+ it('should redirect to auto login', () => {
17
+ expect(shouldRedirectToAutoLogin).toBeTruthy();
18
+ });
19
+ }
20
+
21
+ function itShouldNotRedirectToAutoLogin() {
22
+ it('should not redirect to auto login', () => {
23
+ expect(shouldRedirectToAutoLogin).toBeFalsy();
24
+ });
25
+ }
26
+
27
+ describe('Autologin: Third Party Cookie', () => {
28
+ let cacheGetSpy: jasmine.Spy;
29
+
30
+ beforeEach(() => {
31
+ cacheGetSpy = spyOn(cache, 'get');
32
+ spyOn(cache, 'set');
33
+ spyOn(location, 'navigateTo');
34
+ spyOn(url, 'getAidDomain').and.returnValue('www.aid.no');
35
+ spyOn(url, 'getCurrentUrl').and.returnValue(
36
+ 'https://avisnavn.no/abo/?query=param'
37
+ );
38
+ });
39
+
40
+ describe('when not logged in first party', () => {
41
+ describe('when already checked third party option', () => {
42
+ beforeEach(async () => {
43
+ cacheGetSpy.and.returnValue(true);
44
+ shouldRedirectToAutoLogin = await thirdPartyCookie();
45
+ });
46
+
47
+ it('should not set already tried cache', () => {
48
+ expect(cache.set).not.toHaveBeenCalled();
49
+ });
50
+ itShouldNotRedirectToAutoLogin();
51
+ });
52
+
53
+ describe('when not logged in via third party', () => {
54
+ beforeEach(async () => {
55
+ fetch.doMockIf(
56
+ `https://www.aid.no/api/pluto/v1/sessions/current`,
57
+ JSON.stringify({
58
+ errors: [
59
+ {
60
+ id: 'xxx-000000000000',
61
+ title: 'xxx',
62
+ detail: 'xxx',
63
+ status: '403',
64
+ code: 'session.not_specified',
65
+ },
66
+ ],
67
+ }),
68
+ {
69
+ status: 403,
70
+ }
71
+ );
72
+ shouldRedirectToAutoLogin = await thirdPartyCookie();
73
+ });
74
+
75
+ itShouldSetAlreadyTriedCache();
76
+ itShouldNotRedirectToAutoLogin();
77
+ });
78
+
79
+ describe('when logged in via third party', () => {
80
+ beforeEach(async () => {
81
+ fetch.doMockIf(
82
+ `https://www.aid.no/api/pluto/v1/sessions/current`,
83
+ JSON.stringify({
84
+ user_name: 'Donald Duck',
85
+ tracking_key: 'key',
86
+ })
87
+ );
88
+ shouldRedirectToAutoLogin = await thirdPartyCookie();
89
+ });
90
+
91
+ itShouldSetAlreadyTriedCache();
92
+ itShouldRedirectToAutoLogin();
93
+ });
94
+ });
95
+ });
@@ -0,0 +1,55 @@
1
+ import { Boolean, Record, Static, String } from 'runtypes';
2
+ import cache from '../cache';
3
+ import log from '../utils/log';
4
+ import { getAidDomain } from '../utils/url';
5
+ import { resolveBadPlutoResponse } from '../clients/pluto';
6
+
7
+ export const CACHE_KEY = 'haveTriedThirdPartyLoginCheck';
8
+ export const CACHE_TTL = 60 * 60 * 1000; // One hour
9
+
10
+ const ServiceSessionSchema = Record({
11
+ user_name: String,
12
+ tracking_key: String,
13
+ });
14
+
15
+ const getAidSession = () =>
16
+ <Promise<Static<typeof ServiceSessionSchema> | null>>fetch(
17
+ `https://${getAidDomain()}/api/pluto/v1/sessions/current`,
18
+ {
19
+ mode: 'cors',
20
+ credentials: 'include',
21
+ }
22
+ )
23
+ .then((response) => {
24
+ if (!response.ok) {
25
+ return resolveBadPlutoResponse(response)
26
+ .then(() => null)
27
+ .catch(() => null);
28
+ }
29
+ return response.json();
30
+ })
31
+ .then((data) => {
32
+ if (!data) {
33
+ return null;
34
+ }
35
+ try {
36
+ return ServiceSessionSchema.check(data);
37
+ } catch (error) {
38
+ log.error(error, { data });
39
+ return null;
40
+ }
41
+ });
42
+
43
+ export default async function thirdPartyCookie() {
44
+ // TODO: Should perhaps use cookie for this? Cache as it stands now only survives on the current page until vi replace it with something more persistent
45
+ if (await cache.get(CACHE_KEY, Boolean)) {
46
+ return false;
47
+ }
48
+ await cache.set(CACHE_KEY, true, CACHE_TTL);
49
+
50
+ const aidSession = await getAidSession();
51
+ if (aidSession) {
52
+ return true;
53
+ }
54
+ return false;
55
+ }