@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,20 +0,0 @@
1
- import fetch from 'jest-fetch-mock';
2
- import backendLog from './mercuryLog';
3
-
4
- describe('Mercury backendlog', () => {
5
- it('should include level in url', () => {
6
- backendLog.error('jest message', {});
7
- expect(fetch).toHaveBeenCalledWith(
8
- expect.stringContaining('/error'),
9
- expect.anything()
10
- );
11
- expect(fetch).toHaveBeenCalledTimes(1);
12
- });
13
-
14
- it('should include additional context as query parameters', () => {
15
- backendLog.error('jest message', { referrer: 'https://www.rb.no/' });
16
- const formData = fetch.mock.calls[0][1]?.body as FormData;
17
-
18
- expect(formData?.get('referrer')).toEqual('https://www.rb.no/');
19
- });
20
- });
@@ -1,67 +0,0 @@
1
- import { getCurrentHostname, getCurrentUrl } from '../utils/url';
2
- import { isBoolean, isNumber, isString } from '../utils/type';
3
-
4
- type Context = Record<string, unknown>;
5
-
6
- /**
7
- * Extracted from mercury.tsx so other calls to mercury can log properly
8
- */
9
- function postLog(url: string, query: { [index: string]: any }) {
10
- const body = new FormData();
11
- Object.keys(query).forEach((key) => body.append(key, query[key]));
12
- const options: RequestInit = {
13
- method: 'POST',
14
- body,
15
- headers: {
16
- Accept: 'application/json',
17
- },
18
- };
19
- fetch(url, options).then((res) => {
20
- if (!res.ok) {
21
- // eslint-disable-next-line no-console
22
- console.error(
23
- `Failed to send log to backend: Error, status: ${res.status}, text: ${res.statusText}`
24
- );
25
- }
26
- });
27
- }
28
-
29
- const backendLog = (level: string, message: string, context: Context) => {
30
- const internalContext: Context = {};
31
- Object.keys(context).forEach((key) => {
32
- const currentContext = context[key];
33
- if (
34
- isString(currentContext) ||
35
- isNumber(currentContext) ||
36
- isBoolean(currentContext)
37
- ) {
38
- internalContext[key] = currentContext;
39
- return;
40
- }
41
- try {
42
- internalContext[key] = JSON.stringify(currentContext);
43
- } catch {
44
- internalContext[key] = currentContext;
45
- }
46
- });
47
- const extendedContext = {
48
- ...internalContext,
49
- message,
50
- url: getCurrentUrl(),
51
- domain: getCurrentHostname(),
52
- };
53
- postLog(`/api/mercury/v1/log/${level}`, extendedContext);
54
- };
55
-
56
- const log = {
57
- error: (message: string, context: Context) =>
58
- backendLog('error', message, context),
59
- warn: (message: string, context: Context) =>
60
- backendLog('warn', message, context),
61
- info: (message: string, context: Context) =>
62
- backendLog('info', message, context),
63
- debug: (message: string, context: Context) =>
64
- backendLog('debug', message, context),
65
- };
66
-
67
- export default log;
@@ -1,70 +0,0 @@
1
- import fetch from 'jest-fetch-mock';
2
- import cache from '../cache';
3
- import log from '../utils/log';
4
- import { getInfo } from './nebula';
5
-
6
- describe('nebula service', () => {
7
- beforeEach(async () => {
8
- await cache.clear();
9
- });
10
-
11
- describe('GET /info', () => {
12
- const userKey = '9ea9680f-c810-4693-a981-ca8e732a8a8f';
13
- const siteDomain = 'www.rb.no';
14
- const browserId = 'fc0bce06-560b-48e4-92f2-840e67178516';
15
-
16
- it('should return user information', async () => {
17
- const response = {
18
- ad_segments: '1022776316,1037513379,1043845105',
19
- ad_segments_user: '1022776316,1037513379,1043845105',
20
- age: 28,
21
- age_user: 28,
22
- birth_year: '1992',
23
- birth_year_user: '1992',
24
- gender: 'M',
25
- gender_user: 'M',
26
- grunnkrets: '19030312',
27
- grunnkrets_user: '19030312',
28
- postcode: '0150',
29
- postcode_user: '0150',
30
- shared_account: false,
31
- shared_account_user: false,
32
- user_grouping_number: '34',
33
- user_grouping_number_user: '34',
34
- };
35
-
36
- fetch.mockResponseOnce(JSON.stringify(response));
37
-
38
- await expect(getInfo(siteDomain, browserId, userKey)).resolves.toEqual({
39
- extraData: response,
40
- });
41
-
42
- expect(fetch).toHaveBeenCalledWith(
43
- `https://services.gcloud.api.no/api/nebula/v1/info?domain=${siteDomain}&browser_id=${browserId}&user_key=${userKey}`
44
- );
45
- });
46
-
47
- it('should fail on runtime validation if gender is boolean', async () => {
48
- fetch.mockResponseOnce(JSON.stringify({ gender: true }));
49
- log.error = jest.fn();
50
-
51
- await expect(
52
- getInfo(userKey, siteDomain, browserId)
53
- ).rejects.toBeUndefined();
54
- });
55
-
56
- it('should pass on runtime validation if unknown property is given', async () => {
57
- const response = {
58
- fullname: 'ra. dean baskaran',
59
- age: 28,
60
- shared_account: false,
61
- };
62
-
63
- fetch.mockResponseOnce(JSON.stringify(response));
64
-
65
- await expect(getInfo(userKey, siteDomain, browserId)).resolves.toEqual({
66
- extraData: response,
67
- });
68
- });
69
- });
70
- });
@@ -1,83 +0,0 @@
1
- import {
2
- Static,
3
- Partial,
4
- Dictionary,
5
- Unknown,
6
- String,
7
- Number,
8
- Boolean,
9
- } from 'runtypes';
10
- import getOrUpdate from '../utils/getOrUpdate';
11
- import { UserAttributes } from '../types';
12
- import log from '../utils/log';
13
-
14
- const InfoSchema = Dictionary(Unknown, String).And(
15
- Partial({
16
- ad_segments: String,
17
- ad_segments_user: String,
18
- amedia_employee: Boolean,
19
- amedia_employee_user: Boolean,
20
- age: Number,
21
- age_user: Number,
22
- birth_year: String,
23
- birth_year_user: String,
24
- gender: String,
25
- gender_user: String,
26
- grunnkrets: String,
27
- grunnkrets_user: String,
28
- postcode: String,
29
- postcode_user: String,
30
- shared_account: Boolean,
31
- shared_account_user: Boolean,
32
- user_grouping_number: String,
33
- user_grouping_number_user: String,
34
- })
35
- );
36
-
37
- const getNebulaData = (
38
- siteDomain: string,
39
- browserId: string,
40
- trackingKey?: string
41
- ) => {
42
- const url = new URL('https://services.gcloud.api.no/api/nebula/v1/info');
43
- url.searchParams.set('domain', siteDomain);
44
- url.searchParams.set('browser_id', browserId);
45
- if (trackingKey) {
46
- /**
47
- * Legacy alert!
48
- * Tracking key (what we use to track what the user is doing) was previously called user_key. This caused confusion
49
- * with user_uuid (which is the real user id). user_key was since renamed
50
- * to tracking_key to
51
- * better separate the two, but nebula still likes the old name
52
- */
53
- url.searchParams.set('user_key', trackingKey);
54
- }
55
- return fetch(url.href)
56
- .then((response) => response.json())
57
- .then((json) => {
58
- try {
59
- return {
60
- ttl: 1000 * 60 * 60 * 5, // Cache 5 mins
61
- data: InfoSchema.check(json),
62
- };
63
- } catch (error) {
64
- log.error(error, { json });
65
- throw error;
66
- }
67
- });
68
- };
69
-
70
- const mapNebulaToUserData = (
71
- data: Static<typeof InfoSchema>
72
- ): Pick<UserAttributes, 'extraData'> => ({
73
- extraData: data,
74
- });
75
-
76
- export const getInfo = (
77
- siteDomain: string,
78
- browserId: string,
79
- trackingKey?: string
80
- ): Promise<Pick<UserAttributes, 'extraData'>> =>
81
- getOrUpdate('getNebulaInfo', InfoSchema, () =>
82
- getNebulaData(siteDomain, browserId, trackingKey)
83
- ).then(mapNebulaToUserData);
@@ -1,262 +0,0 @@
1
- import fetch from 'jest-fetch-mock';
2
- import cache from '../cache';
3
- import store from '../store';
4
- import { getCurrentSession, removeSession } from './pluto';
5
- import { Logger, setLogger } from '../utils/log';
6
- import { UserAttributes } from '../types';
7
- import { version } from '../../eik.json';
8
- import anything = jasmine.anything;
9
-
10
- beforeEach(async () => {
11
- await cache.clear();
12
- });
13
-
14
- const userUUID = '3-1-33-7';
15
- const userName = 'Earl Hickey';
16
- const userTrackingKey = 'some tracking key';
17
- const plutoLoggedInResponse = {
18
- created_at:
19
- 'Wed Apr 28 2021 16:02:04 GMT+0200 (Central European Summer Time)',
20
- updated_at:
21
- 'Wed Apr 28 2021 16:02:04 GMT+0200 (Central European Summer Time)',
22
- user_uuid: userUUID,
23
- user_name: userName,
24
- tracking_key: userTrackingKey,
25
- };
26
-
27
- let log: Logger;
28
- beforeEach(() => {
29
- log = {
30
- debug: jest.fn(),
31
- info: jest.fn(),
32
- warn: jest.fn(),
33
- error: jest.fn(),
34
- };
35
- setLogger(log);
36
- });
37
-
38
- function itShouldNotHaveLoggedAnything() {
39
- it('should not have logged anything', () => {
40
- expect(log.debug).not.toHaveBeenCalled();
41
- expect(log.info).not.toHaveBeenCalled();
42
- expect(log.warn).not.toHaveBeenCalled();
43
- expect(log.error).not.toHaveBeenCalled();
44
- });
45
- }
46
-
47
- describe('Pluto client', () => {
48
- describe('getCurrentSession()', () => {
49
- beforeEach(() => {
50
- jest.spyOn(store, 'merge');
51
- });
52
- let currentSession: UserAttributes;
53
- function itShouldReturnSessionData() {
54
- it('should return session data', async () => {
55
- expect(currentSession).toEqual({
56
- uuid: userUUID,
57
- name: userName,
58
- trackingKey: userTrackingKey,
59
- });
60
- });
61
- }
62
- function itShouldReturnNoSessionData() {
63
- it('should return session data', async () => {
64
- expect(currentSession).toEqual({
65
- uuid: null,
66
- name: null,
67
- trackingKey: null,
68
- });
69
- });
70
- }
71
- function itShouldNotSetEmergencyModeState() {
72
- it('should not set emergency mode state', () => {
73
- expect(store.merge).not.toHaveBeenCalledWith('state', {
74
- emergencyMode: anything(),
75
- });
76
- });
77
- }
78
-
79
- function itShouldSetEmergencyModeState(emergencyModes: string[]) {
80
- it('should set emergency mode states', () => {
81
- expect(store.merge).toHaveBeenCalledWith('state', {
82
- emergencyMode: emergencyModes,
83
- });
84
- });
85
- }
86
-
87
- describe('when user is logged in ', () => {
88
- describe('When cache is empty', () => {
89
- beforeEach(async () => {
90
- fetch.mockResponseOnce(JSON.stringify(plutoLoggedInResponse));
91
- currentSession = await getCurrentSession();
92
- });
93
- it('should call Pluto', () => {
94
- expect(fetch).toHaveBeenCalledTimes(1);
95
- });
96
- itShouldReturnSessionData();
97
- itShouldNotSetEmergencyModeState();
98
- });
99
- describe('When cache is not empty', () => {
100
- beforeEach(async () => {
101
- cache.set('getCurrentSession', plutoLoggedInResponse, 60000);
102
- currentSession = await getCurrentSession();
103
- });
104
- it('should not call Pluto', () => {
105
- expect(fetch).toHaveBeenCalledTimes(0);
106
- });
107
- itShouldReturnSessionData();
108
- itShouldNotSetEmergencyModeState();
109
- });
110
-
111
- describe('when single emergency mode is set', () => {
112
- beforeEach(async () => {
113
- fetch.mockResponseOnce(() =>
114
- Promise.resolve({
115
- init: {
116
- status: 200,
117
- headers: {
118
- 'x-emergency-mode': 'aid',
119
- },
120
- },
121
- body: JSON.stringify(plutoLoggedInResponse),
122
- })
123
- );
124
- currentSession = await getCurrentSession();
125
- });
126
- itShouldSetEmergencyModeState(['aid']);
127
- });
128
-
129
- describe('when multiple emergency modes is set', () => {
130
- beforeEach(async () => {
131
- fetch.mockResponseOnce(() =>
132
- Promise.resolve({
133
- init: {
134
- status: 200,
135
- headers: {
136
- 'x-emergency-mode': 'aid,paywall',
137
- },
138
- },
139
- body: JSON.stringify(plutoLoggedInResponse),
140
- })
141
- );
142
- currentSession = await getCurrentSession();
143
- });
144
- itShouldSetEmergencyModeState(['aid', 'paywall']);
145
- });
146
- });
147
-
148
- describe('when user is not logged in', () => {
149
- describe('When cache is empty', () => {
150
- beforeEach(async () => {
151
- fetch.mockResponseOnce(() =>
152
- Promise.resolve({
153
- init: { status: 403 },
154
- body: '{"errors": [{"code": "session.not_found"}]}',
155
- })
156
- );
157
- currentSession = await getCurrentSession();
158
- });
159
- it('should call Pluto', () => {
160
- expect(fetch).toHaveBeenCalledTimes(1);
161
- });
162
- itShouldNotHaveLoggedAnything();
163
- itShouldReturnNoSessionData();
164
- itShouldNotSetEmergencyModeState();
165
- });
166
- describe('When cache is not empty', () => {
167
- beforeEach(async () => {
168
- cache.set('getCurrentSession', {}, 60000);
169
- currentSession = await getCurrentSession();
170
- });
171
- it('should not call Pluto', () => {
172
- expect(fetch).toHaveBeenCalledTimes(0);
173
- });
174
- itShouldNotHaveLoggedAnything();
175
- itShouldReturnNoSessionData();
176
- itShouldNotSetEmergencyModeState();
177
- });
178
- describe('when session is invalid for domain', () => {
179
- beforeEach(async () => {
180
- fetch.mockResponseOnce(() =>
181
- Promise.resolve({
182
- init: { status: 403 },
183
- body: '{"errors": [{"code": "session.invalid_for_domain"}]}',
184
- })
185
- );
186
- currentSession = await getCurrentSession();
187
- });
188
- it('should have logged a warning', () => {
189
- expect(log.warn).toHaveBeenCalledWith(
190
- 'Pluto responded with HTTP/403: (session.invalid_for_domain) while fetching current session',
191
- {
192
- error: { code: 'session.invalid_for_domain' },
193
- origin: '@amedia/user',
194
- originVersion: version,
195
- response: expect.any(Object),
196
- }
197
- );
198
- });
199
- itShouldNotSetEmergencyModeState();
200
- });
201
- describe('when session is no longer valid', () => {
202
- beforeEach(async () => {
203
- fetch.mockResponseOnce(() =>
204
- Promise.resolve({
205
- init: { status: 404 },
206
- body: '{"errors":[{"id":"f84ea34e-d9eb-11eb-afe7-000000000000","title":"No currentSession found","detail":"Got currentSession not found error","status":"404","code":"session.not_found"}]}\n',
207
- })
208
- );
209
- currentSession = await getCurrentSession();
210
- });
211
- itShouldNotHaveLoggedAnything();
212
- itShouldNotSetEmergencyModeState();
213
- });
214
-
215
- describe('when single emergency mode is set', () => {
216
- beforeEach(async () => {
217
- fetch.mockResponseOnce(() =>
218
- Promise.resolve({
219
- init: {
220
- status: 403,
221
- headers: {
222
- 'x-emergency-mode': 'aid',
223
- },
224
- },
225
- body: '{"errors": [{"code": "session.invalid_for_domain"}]}',
226
- })
227
- );
228
- currentSession = await getCurrentSession();
229
- });
230
- itShouldSetEmergencyModeState(['aid']);
231
- });
232
-
233
- describe('when multiple emergency modes is set', () => {
234
- beforeEach(async () => {
235
- fetch.mockResponseOnce(() =>
236
- Promise.resolve({
237
- init: {
238
- status: 403,
239
- headers: {
240
- 'x-emergency-mode': 'aid,paywall',
241
- },
242
- },
243
- body: '{"errors": [{"code": "session.invalid_for_domain"}]}',
244
- })
245
- );
246
- currentSession = await getCurrentSession();
247
- });
248
- itShouldSetEmergencyModeState(['aid', 'paywall']);
249
- });
250
- });
251
- });
252
-
253
- describe('removeSession()', () => {
254
- it('should call Plut session delete', () => {
255
- removeSession('www.rb.no');
256
- expect(fetch).toHaveBeenCalledWith(
257
- '/api/pluto/v1/sessions/current?publication_domain=www.rb.no',
258
- { method: 'DELETE' }
259
- );
260
- });
261
- });
262
- });
@@ -1,126 +0,0 @@
1
- import { Partial, Record, Static, String, Array } from 'runtypes';
2
- import log from '../utils/log';
3
- import getOrUpdate from '../utils/getOrUpdate';
4
- import store from '../store';
5
- import { UserAttributes } from '../types';
6
- import { isAbortedNetworkError } from '../utils/networkError';
7
-
8
- const ServiceSessionSchema = Partial({
9
- user_uuid: String,
10
- user_name: String,
11
- tracking_key: String,
12
- });
13
-
14
- const mapSessionToUserAttributes = (
15
- session: Static<typeof ServiceSessionSchema>
16
- ): UserAttributes => ({
17
- uuid: session.user_uuid || null,
18
- name: session.user_name || null,
19
- trackingKey: session.tracking_key || null,
20
- });
21
-
22
- const PlutoErrorSchema = Record({
23
- code: String,
24
- });
25
-
26
- const PlutoErrorsSchema = Record({
27
- errors: Array(PlutoErrorSchema),
28
- });
29
-
30
- const IGNORED_CODES = [
31
- 'session.not_found',
32
- 'session.not_specified',
33
- 'user.deactivated',
34
- ];
35
- const WARNING_CODE = ['session.invalid_for_domain', 'user.not_found'];
36
-
37
- export const resolveBadPlutoResponse = async (response: Response) => {
38
- let error: Static<typeof PlutoErrorSchema>;
39
- const responseClone = response.clone(); // Clone it so we can log pure response if JSON parse fails
40
- try {
41
- [error] = PlutoErrorsSchema.check(await response.json()).errors;
42
- } catch (e) {
43
- if (isAbortedNetworkError(e?.message)) {
44
- return Promise.resolve();
45
- }
46
- log.warn('Unable to parse error body from pluto', {
47
- error: e,
48
- response: responseClone,
49
- });
50
- return Promise.reject(e);
51
- }
52
-
53
- if (IGNORED_CODES.includes(error?.code)) {
54
- return Promise.resolve();
55
- }
56
-
57
- if (WARNING_CODE.includes(error?.code)) {
58
- log.warn(
59
- `Pluto responded with HTTP/${response.status}: (${error.code}) while fetching current session`,
60
- { error, response }
61
- );
62
- return Promise.resolve();
63
- }
64
- log.error(
65
- `Pluto responded with HTTP/${response.status}: ${response.statusText}) when fetching current session`,
66
- { error, response }
67
- );
68
- return Promise.reject();
69
- };
70
-
71
- const fetchCurrentSession = () =>
72
- fetch(`/api/pluto/v1/sessions/current`)
73
- .then((response) => {
74
- const emergencyMode = response.headers
75
- .get('x-emergency-mode')
76
- ?.split(',');
77
- if (emergencyMode) {
78
- store.merge('state', {
79
- emergencyMode,
80
- });
81
- }
82
- if (!response.ok) {
83
- return resolveBadPlutoResponse(response).then(() => ({}));
84
- }
85
- return response.json();
86
- })
87
- .then((json) => {
88
- const nodata = { ttl: -1, data: json };
89
-
90
- // We are probably logged out in this case.
91
- if (Object.keys(json).length === 0) {
92
- return nodata;
93
- }
94
- try {
95
- return {
96
- ttl: 10000,
97
- data: ServiceSessionSchema.check(json),
98
- };
99
- } catch (error) {
100
- log.error(error, { json });
101
- return nodata;
102
- }
103
- });
104
-
105
- export const getCurrentSession = async (): Promise<UserAttributes> =>
106
- getOrUpdate(
107
- 'getCurrentSession',
108
- ServiceSessionSchema,
109
- fetchCurrentSession
110
- ).then((currentSession) => mapSessionToUserAttributes(currentSession));
111
-
112
- export const removeSession = async (domain: string) =>
113
- fetch(`/api/pluto/v1/sessions/current?publication_domain=${domain}`, {
114
- method: 'DELETE',
115
- }).then((res) => {
116
- if (!res.ok) {
117
- if (res.status === 403 || res.status === 404) {
118
- // No session to log out. Ignoring
119
- return;
120
- }
121
- throw new Error(
122
- `Error, could not perform deleteRequest. Status: ${res.status} Text: ${res.statusText}`
123
- );
124
- }
125
- store.merge('state', { isLoggedIn: false });
126
- });
@@ -1,40 +0,0 @@
1
- import { dispatch, listenWithExclusivity } from '../utils/customEventWrapper';
2
- import { activate } from '../actions/authorization';
3
- import getGlobalThis from '../utils/getGlobalThis';
4
- import { getCurrentSiteDomain } from '../utils/url';
5
-
6
- export enum ActivationEvents {
7
- REQUEST_ACTIVATION = 'amedia-user.activation.request-activation',
8
- ON_ACTIVATION_COMPLETE = 'amedia-user.activation.on-activation-complete',
9
- }
10
-
11
- declare global {
12
- interface WindowEventMap {
13
- [ActivationEvents.REQUEST_ACTIVATION]: CustomEvent<{
14
- accessFeatures: string[];
15
- siteDomain?: string;
16
- }>;
17
- [ActivationEvents.ON_ACTIVATION_COMPLETE]: CustomEvent<{
18
- accessFeatures: string[];
19
- }>;
20
- }
21
- }
22
-
23
- export const listenForActivationRequests = () => {
24
- listenWithExclusivity(ActivationEvents.REQUEST_ACTIVATION, (evt) => {
25
- activate(
26
- evt.detail.accessFeatures,
27
- evt.detail.siteDomain || getCurrentSiteDomain()
28
- ).then((accessFeatures) => {
29
- dispatch(
30
- new CustomEvent(ActivationEvents.ON_ACTIVATION_COMPLETE, {
31
- detail: { accessFeatures },
32
- })
33
- );
34
- });
35
- });
36
- };
37
-
38
- if (!getGlobalThis().amediaUserTestMode) {
39
- listenForActivationRequests();
40
- }
@@ -1,34 +0,0 @@
1
- import { dispatch, listenWithExclusivity } from '../utils/customEventWrapper';
2
- import { login, logout } from '../actions/authentication';
3
-
4
- export enum AuthenticationEvents {
5
- REQUEST_LOGIN = 'amedia-user.authentication.request-login',
6
- REQUEST_LOGOUT = 'amedia-user.authentication.request-logout',
7
-
8
- ON_LOGGED_OUT = 'amedia-user.authentication.on-logged-out',
9
- }
10
-
11
- declare global {
12
- interface WindowEventMap {
13
- [AuthenticationEvents.REQUEST_LOGIN]: CustomEvent<{
14
- requestedUrl: string;
15
- }>;
16
- [AuthenticationEvents.REQUEST_LOGOUT]: CustomEvent<{
17
- onLoggedOut: () => void;
18
- }>;
19
- [AuthenticationEvents.ON_LOGGED_OUT]: CustomEvent;
20
- }
21
- }
22
-
23
- export const listenForAuthenticationRequests = () => {
24
- listenWithExclusivity(AuthenticationEvents.REQUEST_LOGIN, (evt) => {
25
- login(evt.detail.requestedUrl);
26
- });
27
-
28
- listenWithExclusivity(AuthenticationEvents.REQUEST_LOGOUT, () => {
29
- logout().finally(() => {
30
- dispatch(new CustomEvent(AuthenticationEvents.ON_LOGGED_OUT));
31
- });
32
- });
33
- };
34
- listenForAuthenticationRequests();