@amedia/user 0.9.0 → 0.10.1

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 (74) hide show
  1. package/.codeclimate.yml +1 -0
  2. package/dist/actions/authentication.d.ts +2 -1
  3. package/dist/actions/authentication.spec.d.ts +4 -0
  4. package/dist/actions/authorization.d.ts +5 -1
  5. package/dist/exceptions/PaywallError.d.ts +7 -0
  6. package/dist/index.d.ts +2 -0
  7. package/dist/index.js +1 -1
  8. package/dist/lib/PaywallUnlocker.d.ts +16 -0
  9. package/dist/lib/PaywallUnlocker.spec.d.ts +4 -0
  10. package/dist/lib/User.d.ts +1 -1
  11. package/dist/lib/cookie.d.ts +1 -1
  12. package/dist/utils/location.d.ts +3 -0
  13. package/esm/actions/authentication.d.ts +5 -0
  14. package/esm/actions/authorization.d.ts +7 -0
  15. package/esm/actions/preferences.d.ts +9 -0
  16. package/esm/actions/preferences.spec.d.ts +1 -0
  17. package/esm/actions/storage.d.ts +1 -0
  18. package/esm/actions/userData.d.ts +2 -0
  19. package/esm/cache/engines/global.d.ts +21 -0
  20. package/esm/cache/engines/global.spec.d.ts +1 -0
  21. package/esm/cache/engines/indexeddb.d.ts +7 -0
  22. package/esm/cache/index.d.ts +11 -0
  23. package/esm/cache/index.spec.d.ts +4 -0
  24. package/esm/cache/types.d.ts +11 -0
  25. package/esm/clients/europa.d.ts +28 -0
  26. package/esm/clients/europa.spec.d.ts +1 -0
  27. package/esm/clients/jupiter.d.ts +30 -0
  28. package/esm/clients/jupiter.spec.d.ts +1 -0
  29. package/esm/clients/mercury.d.ts +18 -0
  30. package/esm/clients/mercury.spec.d.ts +4 -0
  31. package/esm/clients/nebula.d.ts +2 -0
  32. package/esm/clients/nebula.spec.d.ts +1 -0
  33. package/esm/clients/pluto.d.ts +3 -0
  34. package/esm/clients/pluto.spec.d.ts +1 -0
  35. package/esm/eventHandlers/activation.d.ts +15 -0
  36. package/esm/eventHandlers/authentication.d.ts +17 -0
  37. package/esm/eventHandlers/userAttributes.d.ts +20 -0
  38. package/esm/exceptions/PaywallError.d.ts +7 -0
  39. package/esm/index-authentcation.spec.d.ts +4 -0
  40. package/esm/index-subscription.spec.d.ts +4 -0
  41. package/esm/index.d.ts +23 -0
  42. package/esm/lib/PaywallUnlocker.d.ts +16 -0
  43. package/esm/lib/PaywallUnlocker.spec.d.ts +4 -0
  44. package/esm/lib/User.d.ts +21 -0
  45. package/esm/lib/cookie.d.ts +5 -0
  46. package/esm/lib/rpc.d.ts +6 -0
  47. package/esm/store/index.d.ts +22 -0
  48. package/esm/store/index.spec.d.ts +1 -0
  49. package/esm/types.d.ts +21 -0
  50. package/esm/user.js +2 -0
  51. package/esm/user.js.map +1 -0
  52. package/esm/utils/customEventWrapper.d.ts +17 -0
  53. package/esm/utils/deepEquals.d.ts +4 -0
  54. package/esm/utils/getOrUpdate.d.ts +6 -0
  55. package/esm/utils/getOrUpdate.spec.d.ts +1 -0
  56. package/esm/utils/location.d.ts +2 -0
  57. package/esm/utils/log.d.ts +26 -0
  58. package/esm/utils/queue.d.ts +12 -0
  59. package/esm/utils/url.d.ts +3 -0
  60. package/esm/utils/url.spec.d.ts +1 -0
  61. package/package.json +1 -1
  62. package/src/actions/authentication.spec.ts +41 -0
  63. package/src/actions/authentication.ts +17 -5
  64. package/src/actions/authorization.ts +58 -3
  65. package/src/actions/preferences.spec.ts +2 -2
  66. package/src/clients/nebula.ts +1 -1
  67. package/src/exceptions/PaywallError.ts +13 -0
  68. package/src/index-subscription.spec.ts +10 -10
  69. package/src/index.ts +3 -0
  70. package/src/lib/PaywallUnlocker.spec.ts +196 -0
  71. package/src/lib/PaywallUnlocker.ts +113 -0
  72. package/src/lib/User.ts +2 -2
  73. package/src/lib/cookie.ts +1 -1
  74. package/src/utils/location.ts +8 -0
@@ -0,0 +1,17 @@
1
+ export declare const setRootElement: (element: any) => void;
2
+ /**
3
+ * This listener MUST be used by all listeners in ../eventHandlers
4
+ * We want to ensure that only _one_ instance of this package actually
5
+ * orchestrates data and performs requests against backends.
6
+ * @param type
7
+ * @param listener
8
+ */
9
+ export declare const listenWithExclusivity: <T extends keyof WindowEventMap>(type: T, listener: (this: Window, ev: WindowEventMap[T]) => void) => void;
10
+ /**
11
+ * Use this for response listeners. (../index.ts) where we want
12
+ * all updates with data - no matter who sent the actual request
13
+ * @param type
14
+ * @param listener
15
+ */
16
+ export declare const listenForAllEvents: <T extends keyof WindowEventMap>(type: T, listener: (this: Window, ev: WindowEventMap[T]) => void) => void;
17
+ export declare const dispatch: <T extends Event>(event: T) => void;
@@ -0,0 +1,4 @@
1
+ /**
2
+ * @see https://dev.to/sanderdebr/deep-equality-checking-of-objects-in-vanilla-javascript-5592
3
+ */
4
+ export declare const deepEquals: (a: unknown, b: unknown) => boolean;
@@ -0,0 +1,6 @@
1
+ import { Runtype, Static } from 'runtypes';
2
+ export declare type DataFetcherWithCacheTTL<T extends Runtype> = Promise<{
3
+ ttl: number;
4
+ data: Static<T>;
5
+ }>;
6
+ export default function getOrUpdate<T extends Runtype>(key: string, schema: T, fetch: () => DataFetcherWithCacheTTL<T>, cacheQualifier?: (cacheData: Static<T>) => boolean): Promise<Static<T>>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ export declare const reload: () => void;
2
+ export declare const replace: (requestedUrl: string) => void;
@@ -0,0 +1,26 @@
1
+ export declare type Logger = {
2
+ debug: (message: string | any, ...extra: any[]) => void;
3
+ info: (message: string | any, ...extra: any[]) => void;
4
+ warn: (message: string | any, ...extra: any[]) => void;
5
+ error: (message: string | any, ...extra: any[]) => void;
6
+ };
7
+ export declare const setLogger: (engine: Logger) => void;
8
+ declare const _default: {
9
+ debug: {
10
+ (...data: any[]): void;
11
+ (message?: any, ...optionalParams: any[]): void;
12
+ };
13
+ info: {
14
+ (...data: any[]): void;
15
+ (message?: any, ...optionalParams: any[]): void;
16
+ };
17
+ warn: {
18
+ (...data: any[]): void;
19
+ (message?: any, ...optionalParams: any[]): void;
20
+ };
21
+ error: {
22
+ (...data: any[]): void;
23
+ (message?: any, ...optionalParams: any[]): void;
24
+ };
25
+ };
26
+ export default _default;
@@ -0,0 +1,12 @@
1
+ declare const _default: {
2
+ add: (key: string, promiseCallbacks: {
3
+ resolve: (PromiseLike: any) => void;
4
+ reject: (reason?: any) => void;
5
+ }) => void;
6
+ getAll: (key: string) => {
7
+ resolve: (PromiseLike: any) => void;
8
+ reject: (reason?: any) => void;
9
+ }[];
10
+ peekQueueSize: (key: string) => number;
11
+ };
12
+ export default _default;
@@ -0,0 +1,3 @@
1
+ export declare const setCurrentHostname: (hostname: string) => void;
2
+ export declare const getCurrentEnvironment: () => string | null;
3
+ export declare const getCurrentPublicationDomain: () => string;
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amedia/user",
3
- "version": "0.9.0",
3
+ "version": "0.10.1",
4
4
  "description": "Client lib for working with aID user and associated data",
5
5
  "repository": "https://github.com/amedia/amedia-user-js",
6
6
  "author": "Amedia Utvikling (ID og data)",
@@ -0,0 +1,41 @@
1
+ /**
2
+ * @jest-environment jsdom
3
+ */
4
+
5
+ import * as url from '../utils/url';
6
+ import * as location from '../utils/location';
7
+ import { login } from './authentication';
8
+ import restoreAllMocks = jest.restoreAllMocks;
9
+
10
+ beforeEach(() => {
11
+ restoreAllMocks();
12
+ });
13
+
14
+ describe('authentication', () => {
15
+ describe('goToLoginPage', () => {
16
+ it('should resolve dev env', () => {
17
+ spyOn(url, 'getCurrentEnvironment').and.returnValue('localhost');
18
+ spyOn(location, 'navigateTo');
19
+ login('current');
20
+ expect(location.navigateTo).toHaveBeenCalledWith(
21
+ 'https://www.aid.no.localhost.api.no/aid/logg_inn/?requestedUrl=current'
22
+ );
23
+ });
24
+ it('should resolve snap5 env', () => {
25
+ spyOn(url, 'getCurrentEnvironment').and.returnValue('snap5');
26
+ spyOn(location, 'navigateTo');
27
+ login('current');
28
+ expect(location.navigateTo).toHaveBeenCalledWith(
29
+ 'https://www-snap5.aid.no/aid/logg_inn/?requestedUrl=current'
30
+ );
31
+ });
32
+ it('should resolve prod env', () => {
33
+ spyOn(url, 'getCurrentEnvironment').and.returnValue('');
34
+ spyOn(location, 'navigateTo');
35
+ login('current');
36
+ expect(location.navigateTo).toHaveBeenCalledWith(
37
+ 'https://www.aid.no/aid/logg_inn/?requestedUrl=current'
38
+ );
39
+ });
40
+ });
41
+ });
@@ -8,14 +8,24 @@ import {
8
8
  } from '../utils/url';
9
9
  import log from '../utils/log';
10
10
  import { UserAttributes } from '../types';
11
+ import store from '../store';
12
+ import { navigateTo } from '../utils/location';
11
13
 
12
- export const login = (requestedUrl: string) => {
14
+ export const login = (requestedUrl: URL | string) => {
15
+ let url = new URL(`https://www.aid.no/aid/logg_inn/`);
13
16
  const environment = getCurrentEnvironment();
14
- const url = new URL(
15
- `https://aid.no${environment && `.${environment}.api.no`}/aid/logg_inn/`
17
+ if (environment === 'localhost') {
18
+ url = new URL(`https://www.aid.no.localhost.api.no/aid/logg_inn/`);
19
+ } else if (environment) {
20
+ url = new URL(`https://www-${environment}.aid.no/aid/logg_inn/`);
21
+ }
22
+ url.searchParams.set(
23
+ 'requestedUrl',
24
+ requestedUrl instanceof URL
25
+ ? requestedUrl.href
26
+ : requestedUrl || window.location.href
16
27
  );
17
- url.searchParams.set('requestedUrl', requestedUrl || window.location.href);
18
- window.location.href = url.href;
28
+ navigateTo(url.href);
19
29
  };
20
30
 
21
31
  function clearCookies() {
@@ -40,3 +50,5 @@ export const logout = async () =>
40
50
  });
41
51
 
42
52
  export const getSession = (): Promise<UserAttributes> => getCurrentSession();
53
+
54
+ export const isLoggedIn = (): boolean => !!store.get('state')?.isLoggedIn;
@@ -1,11 +1,18 @@
1
- import { checkForAccess } from '../clients/jupiter';
1
+ import {
2
+ checkForAccess,
3
+ getNonUserAccess,
4
+ getVstoken,
5
+ } from '../clients/jupiter';
2
6
  import { getCurrentPublicationDomain } from '../utils/url';
3
7
  import { UserAttributes } from '../types';
4
8
  import { activateSubscription, UserDeactivatedError } from '../clients/mercury';
5
9
  import { logout } from './authentication';
10
+ import { getCookie, setCookie } from '../lib/cookie';
6
11
 
7
- export const getAccess = (): Promise<Pick<UserAttributes, 'access'>> =>
8
- checkForAccess(getCurrentPublicationDomain(), ['newspaper']);
12
+ export const getAccess = (
13
+ accessFeatures: string[] = ['newspaper']
14
+ ): Promise<Pick<UserAttributes, 'access'>> =>
15
+ checkForAccess(getCurrentPublicationDomain(), accessFeatures);
9
16
 
10
17
  export const activate = (accessFeatures: string[]): Promise<boolean> => {
11
18
  try {
@@ -18,3 +25,51 @@ export const activate = (accessFeatures: string[]): Promise<boolean> => {
18
25
  throw error;
19
26
  }
20
27
  };
28
+
29
+ export const hasAccess = (
30
+ currentAccessFeatures: string[],
31
+ requestedAccessFeatures: string[]
32
+ ): boolean =>
33
+ requestedAccessFeatures.filter((requestedAccessFeature) =>
34
+ currentAccessFeatures.includes(requestedAccessFeature)
35
+ ).length > 0;
36
+
37
+ export const setAccessCookies = async (publicationDomain): Promise<boolean> => {
38
+ const vstoken = await getVstoken(publicationDomain);
39
+ if (vstoken.status === 'success') {
40
+ /**
41
+ * The VSTOKEN cookie will live for 365 days, but a timestamp in the payload will ensure that it cannot
42
+ * be used to gain access for that long. The reason we want the cookie to live long is that it's also
43
+ * used to keep subscribers from seeing ads for buying the subscription they already have.
44
+ */
45
+ setCookie('VSTOKEN', vstoken.cookie, 365, '/');
46
+ return true;
47
+ }
48
+ const vstoken2 = await getNonUserAccess(publicationDomain);
49
+ if (vstoken2.status === 'success') {
50
+ setCookie('VSTOKEN2', vstoken2.vstoken_cookie, 1, '/');
51
+ return true;
52
+ }
53
+ return false;
54
+ };
55
+
56
+ export const hasRecentlyTriedToUnlockPaywall = (): boolean => {
57
+ const cookie = getCookie('aid-paywall-check-performed');
58
+ if (!cookie) {
59
+ return false;
60
+ }
61
+ if (Array.isArray(cookie)) {
62
+ return cookie.filter((value) => value === window.location.href).length > 0;
63
+ }
64
+ return cookie === window.location.href;
65
+ };
66
+
67
+ export const setHasTriedToUnlockPaywall = (): void => {
68
+ const url = new URL(window.location.href);
69
+ url.searchParams.set('access', 'granted');
70
+
71
+ const expires = new Date();
72
+ expires.setTime(expires.getTime() + 2 * 60 * 1000); // Add two minutes
73
+
74
+ setCookie('aid-paywall-check-performed', url.href, expires);
75
+ };
@@ -2,9 +2,9 @@ import fetch from 'jest-fetch-mock';
2
2
  import cache from '../cache';
3
3
  import { getPrivacyPreferences } from './preferences';
4
4
 
5
- beforeEach(() => {
5
+ beforeEach(async () => {
6
6
  fetch.resetMocks();
7
- cache.clear();
7
+ await cache.clear();
8
8
  });
9
9
 
10
10
  const europaResponse = {
@@ -43,7 +43,7 @@ const getNebulaData = (
43
43
  if (trackingKey) {
44
44
  url.searchParams.set('user_key', trackingKey);
45
45
  }
46
- return fetch(url.toString())
46
+ return fetch(url.href)
47
47
  .then((response) => response.json())
48
48
  .then((json) => {
49
49
  try {
@@ -0,0 +1,13 @@
1
+ class PaywallError extends Error {
2
+ static ERROR_RELOADED_NO_ACCESS = 'RELOADED_NO_ACCESS';
3
+
4
+ static ERROR_ENABLING_ACCESS_FAILED = 'ENABLING_ACCESS_FAILED';
5
+
6
+ public code: string;
7
+
8
+ constructor(message: string, code: string) {
9
+ super(message);
10
+ this.code = code;
11
+ }
12
+ }
13
+ export default PaywallError;
@@ -32,7 +32,7 @@ describe('Public endpoint - userdata', () => {
32
32
  });
33
33
 
34
34
  const onUserUpdate = jest.fn();
35
- new User().withAttributes('name').subscribe(onUserUpdate);
35
+ new User().withAttributes(['name']).subscribe(onUserUpdate);
36
36
 
37
37
  expect(onUserUpdate).toHaveBeenCalledWith({
38
38
  attributes: {
@@ -48,10 +48,10 @@ describe('Public endpoint - userdata', () => {
48
48
  });
49
49
 
50
50
  const onUserUpdate1 = jest.fn();
51
- new User().withAttributes('name').subscribe(onUserUpdate1);
51
+ new User().withAttributes(['name']).subscribe(onUserUpdate1);
52
52
 
53
53
  const onUserUpdate2 = jest.fn();
54
- new User().withAttributes('name').subscribe(onUserUpdate2);
54
+ new User().withAttributes(['name']).subscribe(onUserUpdate2);
55
55
 
56
56
  expect(onUserUpdate1).toHaveBeenCalledTimes(1);
57
57
  expect(onUserUpdate1).toHaveBeenCalledWith({
@@ -81,10 +81,10 @@ describe('Public endpoint - userdata', () => {
81
81
  });
82
82
 
83
83
  const firstOnUserUpdate = jest.fn();
84
- new User().withAttributes('name').subscribe(firstOnUserUpdate);
84
+ new User().withAttributes(['name']).subscribe(firstOnUserUpdate);
85
85
 
86
86
  const secondOnUserUpdate = jest.fn();
87
- new User().withAttributes('name').subscribe(secondOnUserUpdate);
87
+ new User().withAttributes(['name']).subscribe(secondOnUserUpdate);
88
88
 
89
89
  expect(firstOnUserUpdate).toHaveBeenCalledTimes(2);
90
90
  expect(firstOnUserUpdate).nthCalledWith(1, { attributes: {}, state: {} });
@@ -113,7 +113,7 @@ describe('Public endpoint - userdata', () => {
113
113
  });
114
114
 
115
115
  const onUserUpdate = jest.fn();
116
- new User().withAttributes('name').subscribe(onUserUpdate);
116
+ new User().withAttributes(['name']).subscribe(onUserUpdate);
117
117
 
118
118
  expect(onUserUpdate).toHaveBeenCalledWith({
119
119
  attributes: {
@@ -132,7 +132,7 @@ describe('Public endpoint - userdata', () => {
132
132
  });
133
133
 
134
134
  const onUserUpdate = jest.fn();
135
- new User().withAttributes('name', 'email').subscribe(onUserUpdate);
135
+ new User().withAttributes(['name', 'email']).subscribe(onUserUpdate);
136
136
 
137
137
  expect(onUserUpdate).toHaveBeenCalledWith({
138
138
  attributes: {
@@ -152,10 +152,10 @@ describe('Public endpoint - userdata', () => {
152
152
  });
153
153
 
154
154
  const firstOnUserUpdate = jest.fn();
155
- new User().withAttributes('name', 'email').subscribe(firstOnUserUpdate);
155
+ new User().withAttributes(['name', 'email']).subscribe(firstOnUserUpdate);
156
156
 
157
157
  const secondOnUserUpdate = jest.fn();
158
- new User().withAttributes('email').subscribe(secondOnUserUpdate);
158
+ new User().withAttributes(['email']).subscribe(secondOnUserUpdate);
159
159
 
160
160
  expect(firstOnUserUpdate).toHaveBeenCalledTimes(1);
161
161
  expect(firstOnUserUpdate).nthCalledWith(1, {
@@ -185,7 +185,7 @@ describe('Public endpoint - userdata', () => {
185
185
 
186
186
  const onUpdate = jest.fn();
187
187
 
188
- new User().withAttributes('name').subscribe(onUpdate);
188
+ new User().withAttributes(['name']).subscribe(onUpdate);
189
189
 
190
190
  expect(onUpdate).toHaveBeenCalledWith({
191
191
  attributes: { name: 'Donald Duck' },
package/src/index.ts CHANGED
@@ -3,6 +3,7 @@ import { ActivationEvents } from './eventHandlers/activation';
3
3
  import { dispatch, listenForAllEvents } from './utils/customEventWrapper';
4
4
  import * as authentication from './actions/authentication';
5
5
  import User from './lib/User';
6
+ import PaywallUnlocker from './lib/PaywallUnlocker';
6
7
 
7
8
  /**
8
9
  * Enables you to subscribe to the user attributes you care about and
@@ -33,3 +34,5 @@ export const tryActivateSubscriptionAccess = (
33
34
  })
34
35
  );
35
36
  });
37
+
38
+ export const paywall = () => new PaywallUnlocker();
@@ -0,0 +1,196 @@
1
+ /**
2
+ * @jest-environment jsdom
3
+ */
4
+
5
+ import fetch from 'jest-fetch-mock';
6
+ import PaywallUnlocker from './PaywallUnlocker';
7
+ import * as authentication from '../actions/authentication';
8
+ import * as authorization from '../actions/authorization';
9
+ import * as pluto from '../clients/pluto';
10
+ import * as location from '../utils/location';
11
+ import store from '../store';
12
+ import PaywallError from '../exceptions/PaywallError';
13
+ import restoreAllMocks = jest.restoreAllMocks;
14
+ import spyOn = jest.spyOn;
15
+
16
+ beforeEach(() => {
17
+ restoreAllMocks();
18
+ fetch.resetMocks();
19
+ });
20
+
21
+ describe('PaywallUnlocker', () => {
22
+ it('should fail if already tried to unlock paywall', () => {
23
+ spyOn(authorization, 'hasRecentlyTriedToUnlockPaywall').mockReturnValue(
24
+ true
25
+ );
26
+ expect(new PaywallUnlocker().tryUnlock()).rejects.toThrow(
27
+ new PaywallError(
28
+ 'Unlock check already performed.',
29
+ PaywallError.ERROR_RELOADED_NO_ACCESS
30
+ )
31
+ );
32
+ });
33
+
34
+ it('should return no access if not logged in', () => {
35
+ spyOn(store, 'get').mockImplementation((key) => {
36
+ if (key === 'state') {
37
+ return { isLoggedIn: false };
38
+ }
39
+ throw new Error('Mock not setup for this');
40
+ });
41
+ spyOn(pluto, 'getCurrentSession').mockResolvedValue({});
42
+
43
+ expect(new PaywallUnlocker().tryUnlock())
44
+ .resolves.toEqual({
45
+ isLoggedIn: false,
46
+ hasAccess: false,
47
+ accessFeatures: [],
48
+ })
49
+ .then(() => {
50
+ expect(pluto.getCurrentSession).toHaveBeenCalledTimes(1);
51
+ });
52
+ });
53
+
54
+ it('should return positive of has access', () => {
55
+ spyOn(authentication, 'isLoggedIn').mockReturnValue(true);
56
+ spyOn(authorization, 'getAccess').mockResolvedValue({
57
+ access: ['newspaper'],
58
+ });
59
+ spyOn(authorization, 'setAccessCookies').mockResolvedValue(true);
60
+ spyOn(authorization, 'setHasTriedToUnlockPaywall');
61
+
62
+ expect(new PaywallUnlocker().tryUnlock())
63
+ .resolves.toEqual({
64
+ isLoggedIn: true,
65
+ hasAccess: true,
66
+ accessFeatures: ['newspaper'],
67
+ })
68
+ .then(() =>
69
+ expect(authorization.setHasTriedToUnlockPaywall).toHaveBeenCalled()
70
+ );
71
+ });
72
+
73
+ it('should try to activate if missing access', (done) => {
74
+ spyOn(authentication, 'isLoggedIn').mockReturnValue(true);
75
+ spyOn(authorization, 'getAccess')
76
+ .mockResolvedValueOnce({ access: [] })
77
+ .mockResolvedValueOnce({ access: ['newspaper'] });
78
+ spyOn(authorization, 'setAccessCookies').mockResolvedValue(true);
79
+ spyOn(authorization, 'setHasTriedToUnlockPaywall');
80
+ spyOn(authorization, 'activate').mockResolvedValue(true);
81
+
82
+ expect(new PaywallUnlocker().tryUnlock())
83
+ .resolves.toEqual({
84
+ isLoggedIn: true,
85
+ hasAccess: true,
86
+ accessFeatures: ['newspaper'],
87
+ })
88
+ .then(() => {
89
+ expect(authorization.activate).toHaveBeenCalled();
90
+ done();
91
+ });
92
+ });
93
+
94
+ it('should try to activate if missing access, but really has no access', (done) => {
95
+ spyOn(authentication, 'isLoggedIn').mockReturnValue(true);
96
+ spyOn(authorization, 'getAccess').mockResolvedValueOnce({ access: [] });
97
+ spyOn(authorization, 'activate').mockResolvedValue(false);
98
+
99
+ expect(new PaywallUnlocker().tryUnlock())
100
+ .resolves.toEqual({
101
+ isLoggedIn: true,
102
+ hasAccess: false,
103
+ accessFeatures: [],
104
+ })
105
+ .then(() => {
106
+ expect(authorization.activate).toHaveBeenCalled();
107
+ done();
108
+ });
109
+ });
110
+
111
+ it("should return what the user has access to even if it's not enough", (done) => {
112
+ spyOn(authentication, 'isLoggedIn').mockReturnValue(true);
113
+ spyOn(authorization, 'getAccess').mockResolvedValueOnce({
114
+ access: ['newspaper'],
115
+ });
116
+ spyOn(authorization, 'activate').mockResolvedValue(false);
117
+
118
+ expect(new PaywallUnlocker().withAccessFeatures(['plussalt']).tryUnlock())
119
+ .resolves.toEqual({
120
+ isLoggedIn: true,
121
+ hasAccess: false,
122
+ accessFeatures: ['newspaper'],
123
+ })
124
+ .then(() => {
125
+ expect(authorization.activate).toHaveBeenCalled();
126
+ done();
127
+ });
128
+ });
129
+
130
+ it('should throw error if failing to set access cookies', () => {
131
+ spyOn(authentication, 'isLoggedIn').mockReturnValue(true);
132
+ spyOn(authorization, 'getAccess').mockResolvedValue({
133
+ access: ['newspaper'],
134
+ });
135
+ spyOn(authorization, 'setAccessCookies').mockResolvedValue(false);
136
+ spyOn(authorization, 'setHasTriedToUnlockPaywall');
137
+
138
+ expect(new PaywallUnlocker().tryUnlock())
139
+ .rejects.toThrow(
140
+ new PaywallError(
141
+ 'Could not set access cookies',
142
+ PaywallError.ERROR_ENABLING_ACCESS_FAILED
143
+ )
144
+ )
145
+ .then(() =>
146
+ expect(authorization.setHasTriedToUnlockPaywall).not.toHaveBeenCalled()
147
+ );
148
+ });
149
+
150
+ it('should perform reload if requested', (done) => {
151
+ spyOn(authentication, 'isLoggedIn').mockReturnValue(true);
152
+ spyOn(authorization, 'getAccess').mockResolvedValue({
153
+ access: ['newspaper'],
154
+ });
155
+ spyOn(authorization, 'setAccessCookies').mockResolvedValue(true);
156
+ spyOn(location, 'reload').mockReturnValue();
157
+ spyOn(location, 'replace').mockReturnValue();
158
+
159
+ new PaywallUnlocker()
160
+ .reloadOnAccess()
161
+ .tryUnlock()
162
+ .then(() => {
163
+ expect(location.reload).toHaveBeenCalled();
164
+ expect(location.replace).not.toHaveBeenCalled();
165
+ done();
166
+ });
167
+ });
168
+
169
+ it('should perform redirect if requested', async () => {
170
+ spyOn(authentication, 'isLoggedIn').mockReturnValue(true);
171
+ spyOn(authorization, 'getAccess').mockResolvedValue({
172
+ access: ['newspaper'],
173
+ });
174
+ spyOn(authorization, 'setAccessCookies').mockResolvedValue(true);
175
+ spyOn(location, 'reload').mockReturnValue();
176
+ spyOn(location, 'replace').mockReturnValue();
177
+
178
+ await new PaywallUnlocker().redirectOnAccess('/some/url').tryUnlock();
179
+ expect(location.reload).not.toHaveBeenCalled();
180
+ expect(location.replace).toHaveBeenCalledWith('/some/url');
181
+ });
182
+
183
+ it('should not perform redirect or reload if not requested', async () => {
184
+ spyOn(authentication, 'isLoggedIn').mockReturnValue(true);
185
+ spyOn(authorization, 'getAccess').mockResolvedValue({
186
+ access: ['newspaper'],
187
+ });
188
+ spyOn(authorization, 'setAccessCookies').mockResolvedValue(true);
189
+ spyOn(location, 'reload').mockReturnValue();
190
+ spyOn(location, 'replace').mockReturnValue();
191
+
192
+ await new PaywallUnlocker().tryUnlock();
193
+ expect(location.reload).not.toHaveBeenCalled();
194
+ expect(location.replace).not.toHaveBeenCalled();
195
+ });
196
+ });