@amedia/user 0.13.35 → 0.13.37

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 (179) hide show
  1. package/dist/user.cjs +1 -1
  2. package/dist/user.cjs.map +3 -3
  3. package/dist/user.d.ts +15 -1
  4. package/dist/user.js +1 -1
  5. package/dist/user.js.map +3 -3
  6. package/package.json +5 -2
  7. package/.codeclimate.yml +0 -8
  8. package/.eslintignore +0 -2
  9. package/.eslintrc +0 -11
  10. package/.prettierrc.json +0 -1
  11. package/@types/amedia-frontend-rpc.d.ts +0 -11
  12. package/@types/browserid.d.ts +0 -4
  13. package/build.js +0 -28
  14. package/checkVersion.cjs +0 -12
  15. package/cloudbuild.json +0 -29
  16. package/cop.json +0 -8
  17. package/dist/actions/authentication.d.ts +0 -4
  18. package/dist/actions/authentication.spec.d.ts +0 -1
  19. package/dist/actions/authorization.d.ts +0 -14
  20. package/dist/actions/authorization.spec.d.ts +0 -4
  21. package/dist/actions/preferences.d.ts +0 -9
  22. package/dist/actions/preferences.spec.d.ts +0 -1
  23. package/dist/actions/storage.d.ts +0 -7
  24. package/dist/actions/userData.d.ts +0 -2
  25. package/dist/actions/userData.spec.d.ts +0 -1
  26. package/dist/autologin/index.d.ts +0 -7
  27. package/dist/autologin/index.spec.d.ts +0 -1
  28. package/dist/autologin/thirdPartyCookie.d.ts +0 -3
  29. package/dist/autologin/thirdPartyCookie.spec.d.ts +0 -1
  30. package/dist/cache/engines/global.d.ts +0 -24
  31. package/dist/cache/engines/global.spec.d.ts +0 -1
  32. package/dist/cache/index.d.ts +0 -11
  33. package/dist/cache/index.spec.d.ts +0 -1
  34. package/dist/cache/types.d.ts +0 -11
  35. package/dist/clients/europa.d.ts +0 -24
  36. package/dist/clients/europa.spec.d.ts +0 -1
  37. package/dist/clients/jupiter.d.ts +0 -30
  38. package/dist/clients/jupiter.spec.d.ts +0 -1
  39. package/dist/clients/mercury.d.ts +0 -3
  40. package/dist/clients/mercury.spec.d.ts +0 -1
  41. package/dist/clients/mercuryLog.d.ts +0 -8
  42. package/dist/clients/mercuryLog.spec.d.ts +0 -1
  43. package/dist/clients/nebula.d.ts +0 -2
  44. package/dist/clients/nebula.spec.d.ts +0 -1
  45. package/dist/clients/pluto.d.ts +0 -4
  46. package/dist/clients/pluto.spec.d.ts +0 -1
  47. package/dist/eventHandlers/activation.d.ts +0 -15
  48. package/dist/eventHandlers/authentication.d.ts +0 -17
  49. package/dist/eventHandlers/eventMap.d.ts +0 -29
  50. package/dist/eventHandlers/state.d.ts +0 -1
  51. package/dist/eventHandlers/state.spec.d.ts +0 -1
  52. package/dist/eventHandlers/storage.d.ts +0 -1
  53. package/dist/eventHandlers/storage.spec.d.ts +0 -1
  54. package/dist/eventHandlers/userAttributes.d.ts +0 -1
  55. package/dist/eventHandlers/userAttributes.spec.d.ts +0 -1
  56. package/dist/exceptions/PaywallError.d.ts +0 -8
  57. package/dist/index-authentcation.spec.d.ts +0 -1
  58. package/dist/index-storage.spec.d.ts +0 -1
  59. package/dist/index-subscription.spec.d.ts +0 -1
  60. package/dist/index.d.ts +0 -20
  61. package/dist/janitor/index.d.ts +0 -10
  62. package/dist/janitor/index.spec.d.ts +0 -1
  63. package/dist/janitor/jobs/accessCookieRefresher.d.ts +0 -1
  64. package/dist/janitor/jobs/accessCookieRefresher.spec.d.ts +0 -1
  65. package/dist/janitor/jobs/daxsubCookie.d.ts +0 -3
  66. package/dist/janitor/jobs/daxsubCookie.spec.d.ts +0 -1
  67. package/dist/janitor/jobs/removeUserStorage.d.ts +0 -1
  68. package/dist/janitor/jobs/removeUserStorage.spec.d.ts +0 -1
  69. package/dist/lib/PaywallUnlockRequest.d.ts +0 -17
  70. package/dist/lib/PaywallUnlockRequest.spec.d.ts +0 -1
  71. package/dist/lib/UserDataRequest.d.ts +0 -22
  72. package/dist/lib/UserDataRequest.spec.d.ts +0 -1
  73. package/dist/lib/cookie.d.ts +0 -9
  74. package/dist/lib/rpc.d.ts +0 -6
  75. package/dist/store/index.d.ts +0 -23
  76. package/dist/store/index.spec.d.ts +0 -1
  77. package/dist/types.d.ts +0 -22
  78. package/dist/utils/customEventWrapper.d.ts +0 -19
  79. package/dist/utils/debouncer.d.ts +0 -26
  80. package/dist/utils/debouncer.spec.d.ts +0 -1
  81. package/dist/utils/deepEquals.d.ts +0 -1
  82. package/dist/utils/expectBootLogs.d.ts +0 -2
  83. package/dist/utils/getOrUpdate.d.ts +0 -6
  84. package/dist/utils/getOrUpdate.spec.d.ts +0 -1
  85. package/dist/utils/localhostCheck.d.ts +0 -1
  86. package/dist/utils/location.d.ts +0 -3
  87. package/dist/utils/log.d.ts +0 -9
  88. package/dist/utils/log.spec.d.ts +0 -1
  89. package/dist/utils/loginState.d.ts +0 -2
  90. package/dist/utils/networkError.d.ts +0 -1
  91. package/dist/utils/queue.d.ts +0 -12
  92. package/dist/utils/type.d.ts +0 -6
  93. package/dist/utils/url.d.ts +0 -6
  94. package/dist/utils/url.spec.d.ts +0 -1
  95. package/eik.json +0 -10
  96. package/global.d.ts +0 -1
  97. package/jest.config.js +0 -7
  98. package/setupJest.js +0 -1
  99. package/src/actions/authentication.spec.ts +0 -51
  100. package/src/actions/authentication.ts +0 -43
  101. package/src/actions/authorization.spec.ts +0 -369
  102. package/src/actions/authorization.ts +0 -117
  103. package/src/actions/preferences.spec.ts +0 -41
  104. package/src/actions/preferences.ts +0 -41
  105. package/src/actions/storage.ts +0 -22
  106. package/src/actions/userData.spec.ts +0 -133
  107. package/src/actions/userData.ts +0 -68
  108. package/src/autologin/index.spec.ts +0 -239
  109. package/src/autologin/index.ts +0 -92
  110. package/src/autologin/thirdPartyCookie.spec.ts +0 -95
  111. package/src/autologin/thirdPartyCookie.ts +0 -55
  112. package/src/cache/engines/global.spec.ts +0 -62
  113. package/src/cache/engines/global.ts +0 -48
  114. package/src/cache/index.spec.ts +0 -130
  115. package/src/cache/index.ts +0 -48
  116. package/src/cache/types.ts +0 -12
  117. package/src/clients/europa.spec.ts +0 -209
  118. package/src/clients/europa.ts +0 -183
  119. package/src/clients/jupiter.spec.ts +0 -179
  120. package/src/clients/jupiter.ts +0 -119
  121. package/src/clients/mercury.spec.ts +0 -59
  122. package/src/clients/mercury.ts +0 -48
  123. package/src/clients/mercuryLog.spec.ts +0 -20
  124. package/src/clients/mercuryLog.ts +0 -67
  125. package/src/clients/nebula.spec.ts +0 -70
  126. package/src/clients/nebula.ts +0 -83
  127. package/src/clients/pluto.spec.ts +0 -165
  128. package/src/clients/pluto.ts +0 -118
  129. package/src/eventHandlers/activation.ts +0 -35
  130. package/src/eventHandlers/authentication.ts +0 -34
  131. package/src/eventHandlers/eventMap.ts +0 -34
  132. package/src/eventHandlers/state.spec.ts +0 -48
  133. package/src/eventHandlers/state.ts +0 -23
  134. package/src/eventHandlers/storage.spec.ts +0 -114
  135. package/src/eventHandlers/storage.ts +0 -45
  136. package/src/eventHandlers/userAttributes.spec.ts +0 -93
  137. package/src/eventHandlers/userAttributes.ts +0 -31
  138. package/src/exceptions/PaywallError.ts +0 -16
  139. package/src/index-authentcation.spec.ts +0 -26
  140. package/src/index-storage.spec.ts +0 -144
  141. package/src/index-subscription.spec.ts +0 -213
  142. package/src/index.ts +0 -59
  143. package/src/janitor/index.spec.ts +0 -18
  144. package/src/janitor/index.ts +0 -59
  145. package/src/janitor/jobs/accessCookieRefresher.spec.ts +0 -213
  146. package/src/janitor/jobs/accessCookieRefresher.ts +0 -98
  147. package/src/janitor/jobs/daxsubCookie.spec.ts +0 -109
  148. package/src/janitor/jobs/daxsubCookie.ts +0 -38
  149. package/src/janitor/jobs/removeUserStorage.spec.ts +0 -34
  150. package/src/janitor/jobs/removeUserStorage.ts +0 -12
  151. package/src/lib/PaywallUnlockRequest.spec.ts +0 -363
  152. package/src/lib/PaywallUnlockRequest.ts +0 -143
  153. package/src/lib/UserDataRequest.spec.ts +0 -77
  154. package/src/lib/UserDataRequest.ts +0 -213
  155. package/src/lib/cookie.ts +0 -121
  156. package/src/lib/rpc.ts +0 -19
  157. package/src/store/index.spec.ts +0 -49
  158. package/src/store/index.ts +0 -64
  159. package/src/types.ts +0 -22
  160. package/src/utils/customEventWrapper.ts +0 -58
  161. package/src/utils/debouncer.spec.ts +0 -252
  162. package/src/utils/debouncer.ts +0 -123
  163. package/src/utils/deepEquals.ts +0 -42
  164. package/src/utils/expectBootLogs.ts +0 -9
  165. package/src/utils/getOrUpdate.spec.ts +0 -166
  166. package/src/utils/getOrUpdate.ts +0 -66
  167. package/src/utils/localhostCheck.ts +0 -9
  168. package/src/utils/location.ts +0 -31
  169. package/src/utils/log.spec.ts +0 -148
  170. package/src/utils/log.ts +0 -124
  171. package/src/utils/loginState.ts +0 -24
  172. package/src/utils/networkError.ts +0 -11
  173. package/src/utils/queue.ts +0 -32
  174. package/src/utils/type.ts +0 -19
  175. package/src/utils/url.spec.ts +0 -33
  176. package/src/utils/url.ts +0 -35
  177. package/testSetup.js +0 -19
  178. package/tsconfig.eslint.json +0 -24
  179. package/tsconfig.json +0 -18
@@ -1,209 +0,0 @@
1
- import fetch from 'jest-fetch-mock';
2
- import cache from '../cache';
3
- import {
4
- updateNamespace,
5
- EuropaSchema,
6
- clearLocalCache,
7
- saveNamespace,
8
- deleteNamespaceKey,
9
- getNamespaces,
10
- getAllNamespaces,
11
- } from './europa';
12
-
13
- beforeEach(() => {
14
- cache.clear();
15
- });
16
-
17
- describe('Europa', () => {
18
- it('saveNamespace should set namespace and return the new value', async () => {
19
- const userInfo = { gender: 'U', post_code: 'U' };
20
- fetch
21
- .mockOnce(JSON.stringify(userInfo)) // data to save 'PUT'
22
- .mockOnce(JSON.stringify({ namespaces: { user_info: userInfo } })); // data retrieved 'GET'
23
-
24
- const namespaceData = await saveNamespace('user_info', userInfo);
25
- expect(fetch).toHaveBeenCalledTimes(2);
26
- expect(namespaceData).toMatchObject({ user_info: userInfo });
27
- });
28
-
29
- it('updateNamespace should update namespace', async () => {
30
- const oldUserInfo = { gender: 'F', post_code: 'U' };
31
- const newUserInfo = { gender: 'M', post_code: '2150' };
32
-
33
- fetch.mockOnce(JSON.stringify({})); // initial response // 'PUT'
34
- fetch.mockOnce(JSON.stringify({ namespaces: { user_info: oldUserInfo } })); // old 'GET'
35
- fetch.mockOnce(JSON.stringify({ namespaces: { user_info: newUserInfo } })); // updated 'GET'
36
-
37
- const old = await saveNamespace('user_info', oldUserInfo);
38
- expect(fetch).toHaveBeenCalledTimes(2);
39
- expect(old).toEqual({ user_info: oldUserInfo });
40
-
41
- const updated = await updateNamespace('user_info', newUserInfo).then(() =>
42
- cache.get('europa', EuropaSchema)
43
- );
44
- expect(updated).toMatchObject({ user_info: newUserInfo });
45
- expect(fetch).toHaveBeenCalledTimes(3);
46
- });
47
-
48
- it('clearLocalCache should remove Europa cache', async () => {
49
- fetch.mockResponse(JSON.stringify({ namespaces: { euucp: { x: 'x' } } }));
50
-
51
- await saveNamespace('euucp', { x: 'x' });
52
- expect(cache.get('europa', EuropaSchema)).resolves.toMatchObject({
53
- euucp: { x: 'x' },
54
- }); // expect something in cache
55
-
56
- await clearLocalCache();
57
- expect(cache.get('europa', EuropaSchema)).resolves.toBeUndefined(); // expect cache to be empty
58
- });
59
-
60
- it('deleteNamespaceKey should remove key from europa', async () => {
61
- fetch
62
- .mockOnce(JSON.stringify({})) // 'GET'
63
- .mockOnce(JSON.stringify({ namespaces: { euucp: { x: 'x', y: 'y' } } })) // 'PUT'
64
- .mockOnce(JSON.stringify({}), { status: 200 }) // 'DELETE'
65
- .mockOnce(JSON.stringify({ namespaces: { euucp: { y: 'y' } } })); // 'PUT'
66
-
67
- const data = { x: 'x', y: 'y' };
68
-
69
- await saveNamespace('euucp', data);
70
- // expect x and y
71
- expect(await cache.get('europa', EuropaSchema)).toEqual(
72
- expect.objectContaining({
73
- euucp: data,
74
- })
75
- );
76
-
77
- await deleteNamespaceKey('euucp', 'x');
78
- // expect only y
79
- expect(await cache.get('europa', EuropaSchema)).toEqual(
80
- expect.objectContaining({
81
- euucp: { y: 'y' },
82
- })
83
- );
84
- });
85
-
86
- it('getAllNamespaces should return all europa namespaces', async () => {
87
- const data = {
88
- euucp: { x: 'x' },
89
- user_info: { gender: 'M', post_code: 'U' },
90
- };
91
-
92
- fetch.mockResponse(JSON.stringify({ namespaces: data }));
93
- expect(await getAllNamespaces()).toMatchObject({ namespaces: data });
94
- });
95
- });
96
-
97
- describe('getNamespaces', () => {
98
- let response: any;
99
- describe('with cold cache', () => {
100
- describe('with one namespace', () => {
101
- const data = { euucp: { x: 'x' } };
102
- beforeEach(async () => {
103
- fetch.mockResponse(JSON.stringify({ namespaces: data }));
104
- response = await getNamespaces(['euucp']);
105
- });
106
- it('should return namespace', () => {
107
- expect(response).toEqual(data);
108
- });
109
- });
110
-
111
- describe('with multiple namespaces', () => {
112
- const data = { euucp: { x: 'x' }, user_info: { a: 'a' } };
113
- beforeEach(async () => {
114
- fetch.mockResponse(JSON.stringify({ namespaces: data }));
115
- response = await getNamespaces(['euucp', 'user_info']);
116
- });
117
- it('should return multiple namespaces', () => {
118
- expect(response).toEqual(data);
119
- });
120
- });
121
-
122
- describe('when doing sequence of calls for different namespaces', () => {
123
- const data = { euucp: { x: 'x' } };
124
- const data2 = { user_info: { a: 'a' } };
125
- let response2: any;
126
- beforeEach(async () => {
127
- fetch.mockResponseOnce(JSON.stringify({ namespaces: data }));
128
- fetch.mockResponseOnce(JSON.stringify({ namespaces: data2 }));
129
- response = await getNamespaces(['euucp']);
130
- response2 = await getNamespaces(['user_info']);
131
- });
132
- it('should return multiple namespaces', () => {
133
- expect(response).toEqual(data);
134
- expect(response2).toEqual(data2);
135
- });
136
- });
137
-
138
- describe('when doing sequence of calls for different namespaces before first response returns', () => {
139
- const data = { euucp: { x: 'x' } };
140
- const data2 = { user_info: { a: 'a' } };
141
- let response2: any;
142
- beforeEach(async () => {
143
- fetch.mockResponseOnce(
144
- JSON.stringify({ namespaces: { ...data, ...data2 } })
145
- );
146
- const futureEuucp = getNamespaces(['euucp']);
147
- response2 = await getNamespaces(['user_info']);
148
- response = await futureEuucp;
149
- });
150
- it('should return euucp in first response', () => {
151
- expect(response).toEqual(data);
152
- });
153
- it('should return user_info in second response', () => {
154
- expect(response2).toEqual(data2);
155
- });
156
- });
157
- });
158
-
159
- describe('with one namespace in cache', () => {
160
- const data = { euucp: { x: 'x' } };
161
- beforeEach(() => {
162
- cache.set('europa', data, 100000);
163
- });
164
-
165
- describe('when requesting cached namespace', () => {
166
- beforeEach(async () => {
167
- response = await getNamespaces(['euucp']);
168
- });
169
- it('should return namespace', () => {
170
- expect(response).toEqual(data);
171
- });
172
- });
173
-
174
- describe('when requesting namespace not found in cache', () => {
175
- const expectedData = {
176
- privacy_preferences: { allow_research_usage: true },
177
- };
178
-
179
- beforeEach(async () => {
180
- fetch.mockResponse(JSON.stringify({ namespaces: expectedData }));
181
- response = await getNamespaces(['privacy_preferences']);
182
- });
183
- it('should return namespace from backend, not from cache', () => {
184
- expect(response).toEqual(expectedData);
185
- });
186
- });
187
-
188
- describe('when requesting multiple namespaces and only one found in cache', () => {
189
- const expectedData = {
190
- privacy_preferences: { allow_research_usage: true },
191
- euucp: { x: 'x' },
192
- };
193
-
194
- beforeEach(async () => {
195
- fetch.mockResponse(JSON.stringify({ namespaces: expectedData }));
196
- response = await getNamespaces(['privacy_preferences', 'euucp']);
197
- });
198
- it('should return namespace from backend, not from cache', () => {
199
- expect(response).toEqual(expectedData);
200
- });
201
- });
202
- });
203
-
204
- it('should require at least one namespace', () => {
205
- expect(getNamespaces([])).rejects.toThrowError(
206
- new Error('namespaces array cannot be of length 0')
207
- );
208
- });
209
- });
@@ -1,183 +0,0 @@
1
- import { Unknown, Dictionary, String, Static } from 'runtypes';
2
-
3
- import cache from '../cache';
4
- import getOrUpdate from '../utils/getOrUpdate';
5
- import log from '../utils/log';
6
- import Debouncer from '../utils/debouncer';
7
-
8
- const CACHE_DURATION = 5 * 60000; // 5 minutes
9
- const DEBOUNCE_WAIT_TIME = 20; // 20ms wait before actually calling Europa
10
-
11
- export const EuropaSchema = Dictionary(Unknown, String);
12
-
13
- export const clearLocalCache = () => cache.remove('europa');
14
-
15
- const doFetch = (url: string, method: string = 'GET', body?: Object) =>
16
- fetch(url, {
17
- method,
18
- body: body && JSON.stringify(body),
19
- headers: {
20
- 'Content-Type': 'application/json',
21
- Accept: 'application/json',
22
- },
23
- });
24
-
25
- function mergeCache(
26
- cachedData: Static<typeof EuropaSchema> | void,
27
- newData: Static<typeof EuropaSchema>
28
- ) {
29
- return Object.entries(newData).reduce(
30
- (mergedNamespaces, [namespace, data]) => ({
31
- ...mergedNamespaces,
32
- [namespace]: data,
33
- }),
34
- cachedData || {}
35
- );
36
- }
37
-
38
- const updateNamespaceInCache = async (namespace: string, data: Object) => {
39
- const cachedData = await cache.get('europa', EuropaSchema);
40
- const updatedData = mergeCache(cachedData, { [namespace]: data });
41
- return cache.set('europa', updatedData, Date.now() + CACHE_DURATION);
42
- };
43
-
44
- export const updateNamespace = async (namespace: string, data: Object) => {
45
- const res = await doFetch(`/api/europa/v1/me/${namespace}`, 'PATCH', data);
46
- if (!res.ok) {
47
- log.error(
48
- `Could not get namespace: ${namespace}, status: ${res.status}, statusText: ${res.statusText}`,
49
- res
50
- );
51
- return {};
52
- }
53
- return updateNamespaceInCache(namespace, data);
54
- };
55
-
56
- const debouncer = new Debouncer<string[], typeof EuropaSchema>(
57
- DEBOUNCE_WAIT_TIME,
58
- [],
59
- Debouncer.stringListParamsAccumulator,
60
- (params) =>
61
- doFetch(`/api/europa/v1/me/${params.join(',')}`).then(async (response) => {
62
- const body = await response.text();
63
- if (!response.ok) {
64
- if (response.status === 500 || response.status === 503) {
65
- log.error(
66
- `Could not get namespaces for: ${params}, status: ${response.status}`,
67
- { response, body }
68
- );
69
- } else {
70
- log.warn(
71
- `Could not get namespaces for: ${params}, status: ${response.status}`,
72
- { response, body }
73
- );
74
- }
75
- return {};
76
- }
77
- return JSON.parse(body).namespaces;
78
- })
79
- );
80
-
81
- export const getNamespaces = async <
82
- S extends { [namespace: string]: { [index: string]: unknown } },
83
- Namespaces extends Array<keyof S>
84
- >(
85
- namespaces: Namespaces,
86
- options: { ignoreCache: boolean } = { ignoreCache: false }
87
- ): Promise<Pick<S, Namespaces[number]>> => {
88
- if (namespaces.length === 0) {
89
- throw new Error('namespaces array cannot be of length 0');
90
- }
91
-
92
- let missingNamespaces = namespaces as string[];
93
- const cachedData = (await cache.get('europa', EuropaSchema)) || {
94
- namespaces: {},
95
- };
96
- if (!options.ignoreCache) {
97
- missingNamespaces = (
98
- cachedData
99
- ? namespaces.filter(
100
- (namespace) =>
101
- !Object.keys(cachedData).includes(namespace as string)
102
- )
103
- : namespaces
104
- ) as string[];
105
- if (cachedData && missingNamespaces.length === 0) {
106
- // Yay! Everything we need is in the cache!
107
- return Promise.resolve(cachedData as Pick<S, Namespaces[number]>);
108
- }
109
- }
110
-
111
- const fetchedNamespaces = await debouncer.perform(missingNamespaces);
112
- Object.entries(fetchedNamespaces).forEach(([namespace, fetchedNamespace]) =>
113
- updateNamespaceInCache(namespace, fetchedNamespace as Object)
114
- );
115
-
116
- return Promise.resolve(
117
- // @ts-ignore
118
- Object.entries(mergeCache(cachedData, fetchedNamespaces))
119
- .filter(([namespace]) => namespaces.includes(namespace))
120
- .reduce(
121
- (returnedEntries, [namespace, data]) => ({
122
- ...returnedEntries,
123
- [namespace]: data,
124
- }),
125
- {} as Pick<S, Namespaces[number]>
126
- )
127
- );
128
- };
129
-
130
- export const saveNamespace = (namespace: string, data: Object) =>
131
- doFetch(`/api/europa/v1/me/${namespace}`, 'PUT', data)
132
- .then((res) => {
133
- if (!res.ok) {
134
- log.error(
135
- `Could not get save namespace, namespace:${namespace} status: ${res.status}, statusText: ${res.statusText}`,
136
- res
137
- );
138
- }
139
- return {};
140
- })
141
- .then(() => getNamespaces([namespace], { ignoreCache: true })); // updates cache
142
-
143
- export const getAllNamespaces = () =>
144
- getOrUpdate(
145
- 'europa',
146
- EuropaSchema,
147
- () =>
148
- doFetch(`/api/europa/v1/me`)
149
- .then((res) => {
150
- if (!res.ok) {
151
- log.error(
152
- `Could not get all namespaces, status: ${res.status}, statusText: ${res.statusText}`,
153
- res
154
- );
155
- return {};
156
- }
157
- return res.json();
158
- })
159
- .then((data) => {
160
- const europaValidData = EuropaSchema.check(data);
161
- try {
162
- return {
163
- ttl: CACHE_DURATION,
164
- data: europaValidData,
165
- };
166
- } catch (error) {
167
- log.error(error, { data });
168
- throw error;
169
- }
170
- }),
171
- () => false
172
- );
173
- export const deleteNamespaceKey = (namespace: string, key: string) =>
174
- doFetch(`/api/europa/v1/me/${namespace}/${key}`, 'DELETE')
175
- .then((res) => {
176
- if (!res.ok) {
177
- log.error(
178
- `Could not get namespace: ${namespace}, status: ${res.status}, statusText: ${res.statusText}`,
179
- res
180
- );
181
- }
182
- })
183
- .then(() => getNamespaces([namespace], { ignoreCache: true })); // updates cache
@@ -1,179 +0,0 @@
1
- import fetch from 'jest-fetch-mock';
2
- import cache from '../cache';
3
- import log from '../utils/log';
4
- import {
5
- checkForAccess,
6
- getUserAccess,
7
- AccessFeatures,
8
- CheckAccessForPaper,
9
- GetVstoken,
10
- GetNonUserAccess,
11
- getNonUserAccess,
12
- } from './jupiter';
13
- import anything = jasmine.anything;
14
-
15
- beforeEach(async () => {
16
- await cache.clear();
17
- });
18
-
19
- describe('jupiter service', () => {
20
- describe('GET /check_access_for_paper', () => {
21
- const publicationDomain = 'www.rb.no';
22
- const accessFeatures: AccessFeatures = ['newspaper'];
23
-
24
- it('should check access for paper', async () => {
25
- const response: CheckAccessForPaper = {
26
- status: 'success',
27
- access: 'granted',
28
- publication: {
29
- domain: 'www.rb.no',
30
- id: 95,
31
- },
32
- access_features: ['amedia_staff', 'newspaper'],
33
- };
34
-
35
- fetch.mockResponseOnce(JSON.stringify(response));
36
-
37
- await expect(
38
- checkForAccess(publicationDomain, accessFeatures)
39
- ).resolves.toEqual({
40
- access: ['amedia_staff', 'newspaper'],
41
- });
42
-
43
- expect(fetch).toHaveBeenCalledWith(
44
- `/api/jupiter/v1/check_access_for_paper/${publicationDomain}/?require=any&access_features=${accessFeatures.join(
45
- ','
46
- )}`
47
- );
48
- });
49
-
50
- it('should deny access for user not logged in', async () => {
51
- fetch.mockResponseOnce(JSON.stringify({ status: 'no_session_found' }), {
52
- status: 400,
53
- });
54
-
55
- await expect(
56
- checkForAccess(publicationDomain, accessFeatures)
57
- ).rejects.toBeUndefined();
58
- });
59
-
60
- it('should fail on runtime validation', async () => {
61
- fetch.mockResponseOnce(JSON.stringify({ access_features: 'foo' }));
62
- log.error = jest.fn();
63
-
64
- await expect(
65
- checkForAccess(publicationDomain, accessFeatures)
66
- ).rejects.toBeUndefined();
67
- });
68
-
69
- it('should not cache when access denied', (done) => {
70
- fetch.mockResponseOnce(
71
- JSON.stringify({
72
- status: 'success',
73
- access: 'denied',
74
- publication: {
75
- domain: 'www.rb.no',
76
- id: 95,
77
- },
78
- access_features: [],
79
- })
80
- );
81
- const cacheSetSpy = spyOn(cache, 'set');
82
- expect(checkForAccess(publicationDomain, accessFeatures))
83
- .resolves.toEqual({ access: [] })
84
- .then(() => {
85
- expect(cacheSetSpy).toHaveBeenCalledWith(
86
- 'checkForAccess',
87
- anything(),
88
- 0
89
- );
90
- })
91
- .then(done);
92
- });
93
- });
94
-
95
- describe('POST /get_vstoken', () => {
96
- const publicationDomain = 'www.rb.no';
97
-
98
- it('should return vstoken', async () => {
99
- const response: GetVstoken = {
100
- status: 'success',
101
- cookie: 'ofofb:16187:amedia_staff,newspaper,plussalt:cc2c2c:rb:jupiter',
102
- access_features: ['newspaper', 'plussalt'],
103
- };
104
-
105
- fetch.mockResponseOnce(JSON.stringify(response));
106
-
107
- await expect(getUserAccess(publicationDomain)).resolves.toEqual(response);
108
-
109
- expect(fetch).toHaveBeenCalledWith(
110
- `/api/jupiter/v1/get_vstoken/${publicationDomain}`,
111
- {
112
- method: 'post',
113
- }
114
- );
115
- });
116
-
117
- it('should deny access for user not logged in', async () => {
118
- fetch.mockResponseOnce(JSON.stringify({ status: 'no_session_found' }), {
119
- status: 400,
120
- });
121
-
122
- await expect(getUserAccess(publicationDomain)).rejects.toThrow(
123
- 'Request not ok (400: Bad Request).'
124
- );
125
- });
126
-
127
- it('should fail on runtime validation', async () => {
128
- fetch.mockResponseOnce(JSON.stringify({ access_features: 'foo' }));
129
- log.error = jest.fn();
130
-
131
- await expect(getUserAccess(publicationDomain)).rejects.toThrow(
132
- 'Expected { status: "success"; cookie: string; access_features: string[]; }, but was incompatible'
133
- );
134
- });
135
- });
136
-
137
- describe('POST /non_user_access', () => {
138
- const publicationDomain = 'www.rb.no';
139
-
140
- it('should return none user access', async () => {
141
- const response: GetNonUserAccess = {
142
- status: 'success',
143
- vstoken_cookie: 'd82ab3842a:2619693230:::rb:jupiter',
144
- uuid: '',
145
- access_features: [],
146
- };
147
-
148
- fetch.mockResponseOnce(JSON.stringify(response));
149
-
150
- await expect(getNonUserAccess(publicationDomain)).resolves.toEqual(
151
- response
152
- );
153
-
154
- expect(fetch).toHaveBeenCalledWith(
155
- `/api/jupiter/v1/non_user_access/${publicationDomain}`,
156
- { method: 'post' }
157
- );
158
- });
159
-
160
- it('should deny access for user not logged in', async () => {
161
- fetch.mockResponseOnce(JSON.stringify({ status: 'no_session_found' }), {
162
- status: 400,
163
- });
164
-
165
- await expect(getNonUserAccess(publicationDomain)).rejects.toThrow(
166
- 'Request not ok (400: Bad Request).'
167
- );
168
- });
169
-
170
- it('should fail on runtime validation', async () => {
171
- fetch.mockResponseOnce(JSON.stringify({ vstoken_cookie: 3 }));
172
- log.error = jest.fn();
173
-
174
- await expect(getNonUserAccess(publicationDomain)).rejects.toThrow(
175
- 'Expected { status: "success"; vstoken_cookie: string; uuid: string; access_features: string[]; }, but was incompatible'
176
- );
177
- });
178
- });
179
- });
@@ -1,119 +0,0 @@
1
- import {
2
- Array,
3
- Literal,
4
- Number,
5
- Record,
6
- Static,
7
- String,
8
- Union,
9
- } from 'runtypes';
10
- import getOrUpdate from '../utils/getOrUpdate';
11
- import { UserAttributes } from '../types';
12
- import log from '../utils/log';
13
-
14
- export type AccessFeatures = string[];
15
-
16
- const PublicationSchema = Record({
17
- id: Number,
18
- domain: String,
19
- });
20
- export const CheckAccessForPaperSchema = Record({
21
- status: Literal('success'),
22
- access: Union(Literal('granted'), Literal('denied')),
23
- publication: PublicationSchema,
24
- access_features: Array(String),
25
- });
26
-
27
- export type CheckAccessForPaper = Static<typeof CheckAccessForPaperSchema>;
28
-
29
- const GetVstokenSchema = Record({
30
- status: Literal('success'),
31
- cookie: String,
32
- access_features: Array(String),
33
- });
34
-
35
- export type GetVstoken = Static<typeof GetVstokenSchema>;
36
-
37
- const GetNonUserAccessSchema = Record({
38
- status: Literal('success'),
39
- vstoken_cookie: String,
40
- uuid: String,
41
- access_features: Array(String),
42
- });
43
-
44
- export type GetNonUserAccess = Static<typeof GetNonUserAccessSchema>;
45
-
46
- export const checkForAccess = (
47
- publicationDomain: string,
48
- accessFeatures: AccessFeatures
49
- ): Promise<Pick<UserAttributes, 'access'>> =>
50
- getOrUpdate('checkForAccess', CheckAccessForPaperSchema, () =>
51
- fetch(
52
- `/api/jupiter/v1/check_access_for_paper/${publicationDomain}/?require=any&access_features=${accessFeatures.join(
53
- ','
54
- )}`
55
- )
56
- .then((response) => {
57
- if (!response.ok) {
58
- // TODO Handle this.
59
- throw new Error(
60
- `Request not ok (${response.status}: ${response.statusText}).`
61
- );
62
- }
63
- return response.json();
64
- })
65
- .then((json) => {
66
- try {
67
- const data = CheckAccessForPaperSchema.check(json);
68
- return {
69
- ttl: data.access === 'granted' ? 1000 * 10 : 0, // 10 seconds
70
- data,
71
- };
72
- } catch (error) {
73
- log.error(error, { json });
74
- throw error;
75
- }
76
- })
77
- ).then((data) => ({ access: data.access_features }));
78
-
79
- export const getUserAccess = (publicationDomain: string): Promise<GetVstoken> =>
80
- fetch(`/api/jupiter/v1/get_vstoken/${publicationDomain}`, { method: 'post' })
81
- .then((response) => {
82
- if (!response.ok) {
83
- throw new Error(
84
- `Request not ok (${response.status}: ${response.statusText}).`
85
- );
86
- }
87
- return response.json();
88
- })
89
- .then((json) => {
90
- try {
91
- return GetVstokenSchema.check(json);
92
- } catch (error) {
93
- log.error(error, { json });
94
- throw error;
95
- }
96
- });
97
-
98
- export const getNonUserAccess = (
99
- publicationDomain: string
100
- ): Promise<GetNonUserAccess> =>
101
- fetch(`/api/jupiter/v1/non_user_access/${publicationDomain}`, {
102
- method: 'post',
103
- })
104
- .then((response) => {
105
- if (!response.ok) {
106
- throw new Error(
107
- `Request not ok (${response.status}: ${response.statusText}).`
108
- );
109
- }
110
- return response.json();
111
- })
112
- .then((json) => {
113
- try {
114
- return GetNonUserAccessSchema.check(json);
115
- } catch (error) {
116
- log.error(error, { json });
117
- throw error;
118
- }
119
- });