@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,117 +0,0 @@
1
- import {
2
- checkForAccess,
3
- getNonUserAccess,
4
- getUserAccess,
5
- } from '../clients/jupiter';
6
- import { getCurrentPublicationDomain, getCurrentUrl } from '../utils/url';
7
- import { UserAttributes } from '../types';
8
- import { activateSubscription, UserDeactivatedError } from '../clients/mercury';
9
- import { logout } from './authentication';
10
- import { getCookie, setCookie } from '../lib/cookie';
11
-
12
- type SetCookieResponse = { success: boolean; accessFeatures: string[] };
13
-
14
- export const getAccess = (
15
- accessFeatures: string[] = ['newspaper']
16
- ): Promise<Pick<UserAttributes, 'access'>> =>
17
- checkForAccess(getCurrentPublicationDomain(), accessFeatures);
18
-
19
- export const activate = async (accessFeatures: string[]): Promise<string[]> => {
20
- try {
21
- return await activateSubscription(accessFeatures);
22
- } catch (error) {
23
- if (error instanceof UserDeactivatedError) {
24
- await logout();
25
- return [];
26
- }
27
- throw error;
28
- }
29
- };
30
-
31
- export const hasAccess = (
32
- currentAccessFeatures: string[],
33
- requestedAccessFeatures: string[]
34
- ): boolean =>
35
- requestedAccessFeatures.length < 1 ||
36
- requestedAccessFeatures.filter((requestedAccessFeature) =>
37
- currentAccessFeatures.includes(requestedAccessFeature)
38
- ).length > 0;
39
-
40
- export const setUserAccessCookie = async (
41
- publicationDomain: string
42
- ): Promise<SetCookieResponse> => {
43
- const vstoken = await getUserAccess(publicationDomain);
44
- if (vstoken.status === 'success') {
45
- /**
46
- * The VSTOKEN cookie will live for 365 days, but a timestamp in the payload will ensure that it cannot
47
- * be used to gain access for that long. The reason we want the cookie to live long is that it's also
48
- * used to keep subscribers from seeing ads for buying the subscription they already have.
49
- */
50
- setCookie('VSTOKEN', vstoken.cookie, 365, '/');
51
- }
52
- return {
53
- success: vstoken.status === 'success',
54
- accessFeatures: vstoken.access_features,
55
- };
56
- };
57
-
58
- export const setNonUserAccessCookie = async (
59
- publicationDomain: string
60
- ): Promise<SetCookieResponse> => {
61
- const vstoken2 = await getNonUserAccess(publicationDomain);
62
- if (vstoken2.status === 'success') {
63
- setCookie('VSTOKEN2', vstoken2.vstoken_cookie, 1, '/');
64
- }
65
- return {
66
- success: vstoken2.status === 'success',
67
- accessFeatures: vstoken2.access_features,
68
- };
69
- };
70
-
71
- export const setAccessCookies = async (
72
- publicationDomain: string
73
- ): Promise<SetCookieResponse> => {
74
- const setters: Array<Promise<SetCookieResponse>> = [];
75
- setters.push(
76
- setUserAccessCookie(publicationDomain).catch(() =>
77
- Promise.resolve({ success: false, accessFeatures: [] })
78
- )
79
- );
80
- setters.push(
81
- setNonUserAccessCookie(publicationDomain).catch(() =>
82
- Promise.resolve({ success: false, accessFeatures: [] })
83
- )
84
- );
85
- return Promise.all(setters).then((results) =>
86
- results.reduce(
87
- (accumulatedResult, result) => ({
88
- success: accumulatedResult.success && result.success,
89
- accessFeatures: accumulatedResult.accessFeatures
90
- .concat(result.accessFeatures)
91
- .filter((v, i, a) => a.indexOf(v) === i) // Remove duplicates by keeping only first copy
92
- .sort(), // We want to keep result deterministic for easy testing
93
- }),
94
- {
95
- success: true,
96
- accessFeatures: [],
97
- }
98
- )
99
- );
100
- };
101
-
102
- export const setHasPerformedPaywallReload = (requestedUrl?: string): void => {
103
- const expires = new Date();
104
- expires.setTime(expires.getTime() + 2 * 60 * 1000); // Add two minutes
105
-
106
- setCookie(
107
- 'aid-paywall-reload-performed',
108
- requestedUrl || getCurrentUrl(),
109
- expires
110
- );
111
- };
112
-
113
- export const hasRecentlyPerformedPaywallReload = (
114
- requestedUrl?: string
115
- ): boolean =>
116
- getCookie('aid-paywall-reload-performed') ===
117
- (requestedUrl || getCurrentUrl());
@@ -1,41 +0,0 @@
1
- import fetch from 'jest-fetch-mock';
2
- import cache from '../cache';
3
- import { getPrivacyPreferences } from './preferences';
4
-
5
- beforeEach(async () => {
6
- await cache.clear();
7
- });
8
-
9
- const europaResponse = {
10
- namespaces: {
11
- privacy_preferences: {
12
- allow_research_usage: 'true',
13
- connect_with_surveys: true,
14
- personalized_ads: 'false',
15
- personalized_content: false,
16
- },
17
- },
18
- };
19
-
20
- describe('privacyPreferences', () => {
21
- it('should return preferences', async () => {
22
- fetch.mockResponse(JSON.stringify(europaResponse));
23
- await getPrivacyPreferences();
24
- expect(fetch).toHaveBeenCalledTimes(1);
25
- });
26
-
27
- it('should use cache if available', async () => {
28
- fetch.mockResponse(JSON.stringify(europaResponse));
29
-
30
- jest.spyOn(cache, 'get').mockReturnValue(
31
- Promise.resolve({
32
- allowResearchUsage: true,
33
- connectWithSurveys: true,
34
- personalizedAds: false,
35
- personalizedContent: false,
36
- })
37
- );
38
- await Promise.all([getPrivacyPreferences(), getPrivacyPreferences()]);
39
- expect(fetch).toHaveBeenCalledTimes(0);
40
- });
41
- });
@@ -1,41 +0,0 @@
1
- import { Record, Boolean } from 'runtypes';
2
- import { getNamespaces } from '../clients/europa';
3
- import { UserAttributes } from '../types';
4
- import getOrUpdate from '../utils/getOrUpdate';
5
-
6
- const CACHE_DURATION = 5 * 60000; // 5 minutes
7
- const PRIVACY_PREFERENCES_CACHE_KEY = 'privacyPreferences';
8
-
9
- export const PrivacyPreferencesSchema = Record({
10
- allowResearchUsage: Boolean,
11
- connectWithSurveys: Boolean,
12
- personalizedAds: Boolean,
13
- personalizedContent: Boolean,
14
- });
15
-
16
- const toBoolean = (val: string | boolean) => val === 'true' || val === true;
17
-
18
- export const getPrivacyPreferences = async (): Promise<
19
- Pick<UserAttributes, 'privacyPreferences'>
20
- > =>
21
- getOrUpdate(PRIVACY_PREFERENCES_CACHE_KEY, PrivacyPreferencesSchema, () =>
22
- getNamespaces(['privacy_preferences']).then((namespaces) => {
23
- const privacyPreferences: any = namespaces.privacy_preferences;
24
-
25
- return {
26
- ttl: CACHE_DURATION,
27
- data: {
28
- allowResearchUsage: toBoolean(
29
- privacyPreferences.allow_research_usage
30
- ),
31
- connectWithSurveys: toBoolean(
32
- privacyPreferences.connect_with_surveys
33
- ),
34
- personalizedAds: toBoolean(privacyPreferences.personalized_ads),
35
- personalizedContent: toBoolean(
36
- privacyPreferences.personalized_content
37
- ),
38
- },
39
- };
40
- })
41
- ).then((data) => ({ privacyPreferences: data }));
@@ -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 { 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
- };
@@ -1,239 +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 * 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
- });