@amedia/user 0.14.17 → 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 (86) hide show
  1. package/dist/user.d.ts +1 -1
  2. package/package.json +2 -3
  3. package/src/actions/authentication.spec.ts +0 -51
  4. package/src/actions/authentication.ts +0 -49
  5. package/src/actions/authorization.spec.ts +0 -377
  6. package/src/actions/authorization.ts +0 -120
  7. package/src/actions/preferences.spec.ts +0 -41
  8. package/src/actions/preferences.ts +0 -41
  9. package/src/actions/storage.ts +0 -22
  10. package/src/actions/userData.spec.ts +0 -133
  11. package/src/actions/userData.ts +0 -68
  12. package/src/autologin/index.spec.ts +0 -264
  13. package/src/autologin/index.ts +0 -113
  14. package/src/autologin/thirdPartyCookie.spec.ts +0 -95
  15. package/src/autologin/thirdPartyCookie.ts +0 -55
  16. package/src/cache/engines/global.spec.ts +0 -62
  17. package/src/cache/engines/global.ts +0 -49
  18. package/src/cache/index.spec.ts +0 -132
  19. package/src/cache/index.ts +0 -48
  20. package/src/cache/types.ts +0 -12
  21. package/src/clients/europa.spec.ts +0 -209
  22. package/src/clients/europa.ts +0 -183
  23. package/src/clients/jupiter.spec.ts +0 -178
  24. package/src/clients/jupiter.ts +0 -119
  25. package/src/clients/mercury.spec.ts +0 -126
  26. package/src/clients/mercury.ts +0 -105
  27. package/src/clients/mercuryLog.spec.ts +0 -20
  28. package/src/clients/mercuryLog.ts +0 -67
  29. package/src/clients/nebula.spec.ts +0 -70
  30. package/src/clients/nebula.ts +0 -83
  31. package/src/clients/pluto.spec.ts +0 -262
  32. package/src/clients/pluto.ts +0 -126
  33. package/src/eventHandlers/activation.ts +0 -40
  34. package/src/eventHandlers/authentication.ts +0 -34
  35. package/src/eventHandlers/eventMap.ts +0 -40
  36. package/src/eventHandlers/navigation.spec.ts +0 -189
  37. package/src/eventHandlers/navigation.ts +0 -58
  38. package/src/eventHandlers/state.spec.ts +0 -48
  39. package/src/eventHandlers/state.ts +0 -23
  40. package/src/eventHandlers/storage.spec.ts +0 -114
  41. package/src/eventHandlers/storage.ts +0 -45
  42. package/src/eventHandlers/userAttributes.spec.ts +0 -93
  43. package/src/eventHandlers/userAttributes.ts +0 -31
  44. package/src/exceptions/FetchTimeoutError.ts +0 -8
  45. package/src/exceptions/PaywallError.ts +0 -16
  46. package/src/index-authentcation.spec.ts +0 -26
  47. package/src/index-storage.spec.ts +0 -144
  48. package/src/index-subscription.spec.ts +0 -213
  49. package/src/index.ts +0 -46
  50. package/src/janitor/index.spec.ts +0 -18
  51. package/src/janitor/index.ts +0 -60
  52. package/src/janitor/jobs/accessCookieRefresher.spec.ts +0 -213
  53. package/src/janitor/jobs/accessCookieRefresher.ts +0 -96
  54. package/src/janitor/jobs/daxsubCookie.spec.ts +0 -109
  55. package/src/janitor/jobs/daxsubCookie.ts +0 -38
  56. package/src/janitor/jobs/removeUserStorage.spec.ts +0 -34
  57. package/src/janitor/jobs/removeUserStorage.ts +0 -12
  58. package/src/lib/PaywallUnlockRequest.spec.ts +0 -446
  59. package/src/lib/PaywallUnlockRequest.ts +0 -161
  60. package/src/lib/UserDataRequest.spec.ts +0 -231
  61. package/src/lib/UserDataRequest.ts +0 -267
  62. package/src/lib/cookie.ts +0 -121
  63. package/src/lib/rpc.ts +0 -19
  64. package/src/store/index.spec.ts +0 -49
  65. package/src/store/index.ts +0 -66
  66. package/src/types.ts +0 -22
  67. package/src/utils/customEventWrapper.spec.ts +0 -237
  68. package/src/utils/customEventWrapper.ts +0 -77
  69. package/src/utils/debouncer.spec.ts +0 -252
  70. package/src/utils/debouncer.ts +0 -123
  71. package/src/utils/deepEquals.ts +0 -42
  72. package/src/utils/expectBootLogs.ts +0 -9
  73. package/src/utils/getGlobalThis.ts +0 -17
  74. package/src/utils/getOrUpdate.spec.ts +0 -166
  75. package/src/utils/getOrUpdate.ts +0 -66
  76. package/src/utils/localhostCheck.ts +0 -10
  77. package/src/utils/location.spec.ts +0 -61
  78. package/src/utils/location.ts +0 -16
  79. package/src/utils/log.spec.ts +0 -177
  80. package/src/utils/log.ts +0 -112
  81. package/src/utils/loginState.ts +0 -24
  82. package/src/utils/networkError.ts +0 -11
  83. package/src/utils/queue.ts +0 -32
  84. package/src/utils/type.ts +0 -19
  85. package/src/utils/url.spec.ts +0 -33
  86. package/src/utils/url.ts +0 -37
@@ -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 }));
@@ -1,22 +0,0 @@
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
- );
@@ -1,133 +0,0 @@
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
- });
@@ -1,68 +0,0 @@
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 { getCurrentSiteDomain } from '../utils/url';
11
-
12
- const getExtraData = () =>
13
- Promise.all([getBrowserId(), whenLoginStateResolved()]).then(
14
- ([browserId, isLoggedIn]) =>
15
- getInfo(
16
- getCurrentSiteDomain(),
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
- };
@@ -1,264 +0,0 @@
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 log from '../utils/log';
9
- import * as location from '../utils/location';
10
- import * as url from '../utils/url';
11
- import * as cookie from '../lib/cookie';
12
- import UserDataRequest from '../lib/UserDataRequest';
13
-
14
- function itShouldNotNavigateAway() {
15
- it('should not navigate away', () => {
16
- expect(location.navigateTo).not.toHaveBeenCalled();
17
- });
18
- }
19
-
20
- function itShouldCallThirdPartyCookieStrategy() {
21
- it('should try third party auto login', () => {
22
- expect(thirdPartyCookie.default).toHaveBeenCalledTimes(1);
23
- });
24
- }
25
-
26
- function itShouldNavigateToAutoLogin(context: string) {
27
- it(`should navigate to auto with context ${context}`, async () => {
28
- expect(location.navigateTo).toHaveBeenCalledWith(
29
- `https://www.aid.no/aid/logg_inn/auto?context=auto_login_${context}&requestedUrl=https%3A%2F%2Fwww.avisnavn.no%2Fabo%2F%3Fquery%3Dparam`
30
- );
31
- });
32
- }
33
-
34
- let getCookieSpy: jasmine.Spy;
35
-
36
- beforeEach(() => {
37
- jest.mock('./thirdPartyCookie');
38
- spyOn(location, 'navigateTo');
39
- spyOn(url, 'getAidDomain').and.returnValue('www.aid.no');
40
- spyOn(url, 'getCurrentUrl').and.returnValue(
41
- 'https://www.avisnavn.no/abo/?query=param'
42
- );
43
- getCookieSpy = spyOn(cookie, 'getCookie').and.returnValue('0');
44
- spyOn(cookie, 'setCookie');
45
- });
46
-
47
- describe('attemptAutoLoginJob', () => {
48
- let shouldPerformAutoLogin = false;
49
-
50
- beforeEach(() => {
51
- shouldPerformAutoLogin = false;
52
- jest
53
- .spyOn(thirdPartyCookie, 'default')
54
- .mockImplementation(() => Promise.resolve(shouldPerformAutoLogin));
55
- });
56
-
57
- describe('when already logged in', () => {
58
- beforeEach(async () => {
59
- jest
60
- .spyOn(UserDataRequest.prototype, 'subscribe')
61
- .mockImplementation((callback) => {
62
- callback({
63
- attributes: {
64
- name: 'Some name',
65
- },
66
- state: {
67
- isLoggedIn: true,
68
- },
69
- });
70
- });
71
- store.set('state', { isLoggedIn: true });
72
- await attemptAutoLoginJob();
73
- });
74
-
75
- it('should not try third party auto login', () => {
76
- expect(thirdPartyCookie.default).not.toHaveBeenCalled();
77
- });
78
- });
79
-
80
- describe('when not already logged in', () => {
81
- beforeEach(async () => {
82
- jest
83
- .spyOn(UserDataRequest.prototype, 'subscribe')
84
- .mockImplementation((callback) => {
85
- callback({
86
- attributes: {},
87
- state: {
88
- isLoggedIn: false,
89
- },
90
- });
91
- });
92
- store.set('state', { isLoggedIn: false });
93
- });
94
-
95
- describe('when in iframe (Dr. Edition)', () => {
96
- let originalTop: Window;
97
- beforeEach(async () => {
98
- originalTop = global.top;
99
- // @ts-ignore
100
- delete global.top; // Set window.top to something other than window.self
101
- // @ts-ignore
102
- global.top = {};
103
- await attemptAutoLoginJob();
104
- });
105
- afterEach(() => {
106
- // @ts-ignore
107
- global.top = originalTop;
108
- });
109
-
110
- itShouldNotNavigateAway();
111
- });
112
-
113
- describe('when a strategy triggers auto login', () => {
114
- beforeEach(async () => {
115
- shouldPerformAutoLogin = true;
116
- attemptAutoLoginJob();
117
- });
118
-
119
- itShouldCallThirdPartyCookieStrategy();
120
- itShouldNavigateToAutoLogin('third_party');
121
- });
122
- describe('when no strategy triggers auto login', () => {
123
- beforeEach(async () => {
124
- await attemptAutoLoginJob();
125
- });
126
-
127
- itShouldCallThirdPartyCookieStrategy();
128
- itShouldNotNavigateAway();
129
- });
130
-
131
- describe('when already tried auto login', () => {
132
- describe('when tried within the last minute', () => {
133
- beforeEach(async () => {
134
- getCookieSpy.and.returnValue(Date.now());
135
- await attemptAutoLoginJob();
136
- });
137
- itShouldCallThirdPartyCookieStrategy();
138
- itShouldNotNavigateAway();
139
- });
140
-
141
- describe('when last attempt is old', () => {
142
- beforeEach(async () => {
143
- getCookieSpy.and.returnValue(
144
- Date.now() - AUTOLOGIN_COOKIE_TTL - 1000
145
- );
146
- await attemptAutoLoginJob();
147
- });
148
- itShouldCallThirdPartyCookieStrategy();
149
- itShouldNotNavigateAway();
150
- });
151
- });
152
-
153
- describe('when in aid emergency mode', () => {
154
- let logWarnSpy: jasmine.Spy;
155
- beforeEach(async () => {
156
- logWarnSpy = spyOn(log, `warn`).and.stub();
157
- store.merge('state', {
158
- emergencyMode: ['aid'],
159
- });
160
- await attemptAutoLoginJob();
161
- });
162
-
163
- it('should not try third party auto login', () => {
164
- expect(thirdPartyCookie.default).not.toHaveBeenCalled();
165
- });
166
-
167
- it('should log warning about being in aid emergency mode', () => {
168
- expect(logWarnSpy).toHaveBeenCalledWith(
169
- 'Autologin prevented. We are in aid emergency mode.',
170
- {
171
- emergencyModes: ['aid'],
172
- }
173
- );
174
- });
175
- });
176
- });
177
- });
178
-
179
- describe('attemptPaywallAutoLogin', () => {
180
- beforeEach(() => {});
181
-
182
- describe('when already logged in', () => {
183
- beforeEach(async () => {
184
- jest
185
- .spyOn(UserDataRequest.prototype, 'subscribe')
186
- .mockImplementation((callback) => {
187
- callback({
188
- attributes: {
189
- name: 'Some name',
190
- },
191
- state: {
192
- isLoggedIn: true,
193
- },
194
- });
195
- });
196
- store.set('state', { isLoggedIn: true });
197
- await attemptPaywallAutoLogin();
198
- });
199
- });
200
-
201
- describe('when not already logged in', () => {
202
- beforeEach(async () => {
203
- jest
204
- .spyOn(UserDataRequest.prototype, 'subscribe')
205
- .mockImplementation((callback) => {
206
- callback({
207
- attributes: {},
208
- state: {
209
- isLoggedIn: false,
210
- },
211
- });
212
- });
213
- store.set('state', { isLoggedIn: false });
214
- });
215
-
216
- describe('when in iframe (Dr. Edition)', () => {
217
- let originalTop: Window;
218
- beforeEach(async () => {
219
- originalTop = global.top;
220
- // @ts-ignore
221
- delete global.top; // Set window.top to something other than window.self
222
- // @ts-ignore
223
- global.top = {};
224
- await attemptPaywallAutoLogin();
225
- });
226
- afterEach(() => {
227
- // @ts-ignore
228
- global.top = originalTop;
229
- });
230
-
231
- itShouldNotNavigateAway();
232
- });
233
-
234
- describe('when not in iframe', () => {
235
- describe('when already tried cookie is not found', () => {
236
- beforeEach(async () => {
237
- getCookieSpy.and.returnValue(undefined);
238
- attemptPaywallAutoLogin();
239
- });
240
- itShouldNavigateToAutoLogin('paywall');
241
- });
242
-
243
- describe('when already tried cookie was found', () => {
244
- describe('when tried within the last minute', () => {
245
- beforeEach(async () => {
246
- getCookieSpy.and.returnValue(Date.now());
247
- await attemptPaywallAutoLogin();
248
- });
249
- itShouldNotNavigateAway();
250
- });
251
-
252
- describe('when last attempt is old', () => {
253
- beforeEach(async () => {
254
- getCookieSpy.and.returnValue(
255
- Date.now() - AUTOLOGIN_COOKIE_TTL - 1000
256
- );
257
- attemptPaywallAutoLogin();
258
- });
259
- itShouldNavigateToAutoLogin('paywall');
260
- });
261
- });
262
- });
263
- });
264
- });
@@ -1,113 +0,0 @@
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
- import store from '../store';
7
- import log from '../utils/log';
8
-
9
- export type Strategies = Array<{
10
- name: string;
11
- handler: () => Promise<boolean>;
12
- }>;
13
-
14
- const AUTOLOGIN_COOKIE = 'has-tried-autologin';
15
- export const AUTOLOGIN_COOKIE_TTL = 60000; // One minute
16
-
17
- function inIframe() {
18
- try {
19
- return window.self !== window.top;
20
- } catch (e) {
21
- return true;
22
- }
23
- }
24
-
25
- function hasAlreadyAttemptedAutoLogin() {
26
- const cookie = getCookie(AUTOLOGIN_COOKIE);
27
- if (cookie && typeof cookie !== 'object') {
28
- try {
29
- if (Date.now() - parseInt(cookie, 10) < AUTOLOGIN_COOKIE_TTL) {
30
- return true;
31
- }
32
- } catch (e) {
33
- removeCookie(AUTOLOGIN_COOKIE);
34
- }
35
- }
36
- setCookie(AUTOLOGIN_COOKIE, Date.now(), Date.now() + AUTOLOGIN_COOKIE_TTL);
37
- return false;
38
- }
39
-
40
- function isInAidEmergencyMode() {
41
- return store.get('state')?.emergencyMode?.includes('aid');
42
- }
43
-
44
- const attemptAutologin = async (strategies: Strategies) => {
45
- if (typeof window === 'undefined' || inIframe()) {
46
- // Avoid auto-login on preview for dr edition and in workers.
47
- return;
48
- }
49
-
50
- const {
51
- state: { isLoggedIn },
52
- } = await new UserDataRequest().fetch();
53
- if (isLoggedIn) {
54
- return;
55
- }
56
-
57
- if (isInAidEmergencyMode()) {
58
- // Avoid auto-login if we are in aid emergency mode
59
- log.warn('Autologin prevented. We are in aid emergency mode.', {
60
- emergencyModes: store.get('state')?.emergencyMode,
61
- });
62
- return;
63
- }
64
-
65
- // eslint-disable-next-line no-restricted-syntax
66
- for (const strategy of strategies) {
67
- // eslint-disable-next-line no-await-in-loop
68
- const shouldTryMoreStrategies = await strategy
69
- .handler()
70
- .then((shouldPerformAutoLogin) => {
71
- if (shouldPerformAutoLogin) {
72
- if (hasAlreadyAttemptedAutoLogin()) {
73
- return false;
74
- }
75
-
76
- // Try to get newspaper cookie
77
- const url = new URL(`https://${getAidDomain()}/aid/logg_inn/auto`);
78
- url.searchParams.set('context', `auto_login_${strategy.name}`);
79
- url.searchParams.set('requestedUrl', getCurrentUrl());
80
- navigateTo(url.href);
81
-
82
- /**
83
- * Don't resolve autologin promise when navigating away.
84
- * This will cause waiting code to execute as if the user did/did not have access
85
- * and will in turn cause flickering and unnecessary (and often aborted) request to
86
- * various backends.
87
- */
88
- return new Promise<boolean>(() => {});
89
- }
90
- return true;
91
- });
92
-
93
- if (!shouldTryMoreStrategies) {
94
- return;
95
- }
96
- }
97
- };
98
-
99
- export const attemptAutoLoginJob = () =>
100
- attemptAutologin([
101
- {
102
- name: 'third_party',
103
- handler: thirdPartyCookie,
104
- },
105
- ]);
106
-
107
- export const attemptPaywallAutoLogin = () =>
108
- attemptAutologin([
109
- {
110
- name: 'paywall',
111
- handler: () => Promise.resolve(true),
112
- },
113
- ]);