@amedia/user 0.12.33 → 0.13.0

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.
@@ -1,14 +1,9 @@
1
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;
2
+ debug: (message: string | Error, context?: Object) => void;
3
+ info: (message: string | Error, context?: Object) => void;
4
+ warn: (message: string | Error, context?: Object) => void;
5
+ error: (message: string | Error, context?: Object) => void;
6
6
  };
7
7
  export declare const setLogger: (engine: Logger) => void;
8
- declare const _default: {
9
- debug: (message: string | any, ...extra: any[]) => void;
10
- info: (message: string | any, ...extra: any[]) => void;
11
- warn: (message: string | any, ...extra: any[]) => void;
12
- error: (message: string | any, ...extra: any[]) => void;
13
- };
8
+ declare const _default: Logger;
14
9
  export default _default;
@@ -0,0 +1 @@
1
+ export {};
package/eik.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "user-js",
3
- "version": "0.12.32",
3
+ "version": "0.13.0",
4
4
  "server": "https://assets.acdn.no",
5
5
  "files": {
6
6
  "user.js": "./esm/user.js",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amedia/user",
3
- "version": "0.12.33",
3
+ "version": "0.13.0",
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)",
@@ -16,13 +16,13 @@ export const getAccess = (
16
16
  ): Promise<Pick<UserAttributes, 'access'>> =>
17
17
  checkForAccess(getCurrentPublicationDomain(), accessFeatures);
18
18
 
19
- export const activate = (accessFeatures: string[]): Promise<boolean> => {
19
+ export const activate = (accessFeatures: string[]): Promise<string[]> => {
20
20
  try {
21
21
  return activateSubscription(accessFeatures);
22
22
  } catch (error) {
23
23
  if (error instanceof UserDeactivatedError) {
24
24
  logout();
25
- return Promise.resolve(false);
25
+ return Promise.resolve([]);
26
26
  }
27
27
  throw error;
28
28
  }
@@ -81,9 +81,33 @@ export const hasRecentlyTriedToUnlockPaywall = (): boolean => {
81
81
 
82
82
  export const setAccessCookies = async (
83
83
  publicationDomain
84
- ): Promise<SetCookieResponse> =>
85
- setUserAccessCookie(publicationDomain) &&
86
- setNonUserAccessCookie(publicationDomain);
84
+ ): Promise<SetCookieResponse> => {
85
+ const setters: Array<Promise<SetCookieResponse>> = [];
86
+ setters.push(
87
+ setUserAccessCookie(publicationDomain).catch(() =>
88
+ Promise.resolve({ success: false, accessFeatures: [] })
89
+ )
90
+ );
91
+ setters.push(
92
+ setNonUserAccessCookie(publicationDomain).catch(() =>
93
+ Promise.resolve({ success: false, accessFeatures: [] })
94
+ )
95
+ );
96
+ return Promise.all(setters).then((results) =>
97
+ results.reduce(
98
+ (accumulatedResult, result) => ({
99
+ success: accumulatedResult.success && result.success,
100
+ accessFeatures: accumulatedResult.accessFeatures
101
+ .concat(result.accessFeatures)
102
+ .filter((v, i, a) => a.indexOf(v) === i),
103
+ }),
104
+ {
105
+ success: true,
106
+ accessFeatures: [],
107
+ }
108
+ )
109
+ );
110
+ };
87
111
 
88
112
  export const setHasTriedToUnlockPaywall = (): void => {
89
113
  const url = new URL(getCurrentUrl());
@@ -53,7 +53,7 @@ export const requestAttributes = (attributes: Array<keyof UserAttributes>) => {
53
53
  store.merge('userAttributes', data);
54
54
  })
55
55
  .catch((error) => {
56
- log.warn('Call rejected', service, error);
56
+ log.warn(`User attribute call failed (${service.toString()})`, error);
57
57
  })
58
58
  );
59
59
  });
@@ -2,7 +2,6 @@ import { Boolean, Record, Static, String } from 'runtypes';
2
2
  import cache from '../cache';
3
3
  import log from '../utils/log';
4
4
  import { getAidDomain } from '../utils/url';
5
- import logValidationError from '../utils/logValidationError';
6
5
 
7
6
  export const CACHE_KEY = 'haveTriedThirdPartyLoginCheck';
8
7
  export const CACHE_TTL = 60 * 60 * 1000; // One hour
@@ -39,7 +38,7 @@ const getAidSession = () =>
39
38
  try {
40
39
  return ServiceSessionSchema.check(data);
41
40
  } catch (error) {
42
- logValidationError('ServiceSessionSchema', error, { data });
41
+ log.error(error);
43
42
  return null;
44
43
  }
45
44
  });
@@ -5,13 +5,14 @@
5
5
  import { Record, String } from 'runtypes';
6
6
  import * as MockDate from 'mockdate';
7
7
  import cache, { setCacheEngine } from '.';
8
- import log from '../utils/log';
8
+ import { setLogger } from '../utils/log';
9
9
  import restoreAllMocks = jest.restoreAllMocks;
10
10
 
11
11
  const TestDataSchema = Record({
12
12
  test: String,
13
13
  });
14
14
 
15
+ let log;
15
16
  let mockEngine;
16
17
  beforeEach(() => {
17
18
  restoreAllMocks();
@@ -25,7 +26,10 @@ beforeEach(() => {
25
26
  };
26
27
  // @ts-ignore
27
28
  setCacheEngine(mockEngine);
28
- log.error = jest.fn();
29
+ log = {
30
+ error: jest.fn(),
31
+ };
32
+ setLogger(log);
29
33
  });
30
34
 
31
35
  describe('Cache', () => {
@@ -65,11 +69,22 @@ describe('Cache', () => {
65
69
  expect(mockEngine.get).toHaveBeenCalledWith('foo');
66
70
  expect(mockEngine.remove).toHaveBeenCalledWith('foo');
67
71
  expect(log.error).toHaveBeenCalledWith(
68
- 'Invalid cache engine schema',
72
+ 'Expected { test: string; }, but was incompatible',
69
73
  {
70
- test: 'Expected string, but was missing',
71
- },
72
- { data: { invalid: 'data' } }
74
+ error: {
75
+ code: 'CONTENT_INCORRECT',
76
+ details: {
77
+ test: 'Expected string, but was missing',
78
+ },
79
+ message: 'Expected { test: string; }, but was incompatible',
80
+ name: 'ValidationError',
81
+ stack: expect.stringMatching(
82
+ /ValidationError: Expected \{ test: string; \}, but was incompatible\n(^\s+at\s.+$\n){3,}/m
83
+ ),
84
+ },
85
+ cacheData: { invalid: 'data' },
86
+ origin: '@amedia/user',
87
+ }
73
88
  );
74
89
  });
75
90
 
@@ -1,8 +1,8 @@
1
1
  import { Static } from 'runtypes';
2
2
  import { RuntypeBase } from 'runtypes/lib/runtype';
3
+ import log from '../utils/log';
3
4
  import globalCache from './engines/global';
4
5
  import { Engine } from './types';
5
- import logValidationError from '../utils/logValidationError';
6
6
 
7
7
  let cacheEngine: Engine;
8
8
 
@@ -33,7 +33,7 @@ const get = async <T extends RuntypeBase>(
33
33
  const typedData = validator.check(cacheEntry.data);
34
34
  return typedData as T;
35
35
  } catch (error) {
36
- logValidationError('cache engine schema', error, { data: cacheEntry.data });
36
+ log.error(error, { cacheData: cacheEntry.data });
37
37
  remove(key);
38
38
  return Promise.resolve();
39
39
  }
@@ -3,7 +3,6 @@ import { Record, Unknown, Dictionary, String } from 'runtypes';
3
3
  import cache from '../cache';
4
4
  import getOrUpdate from '../utils/getOrUpdate';
5
5
  import log from '../utils/log';
6
- import logValidationError from '../utils/logValidationError';
7
6
 
8
7
  const CACHE_DURATION = 5 * 60000; // 5 minutes
9
8
 
@@ -117,7 +116,7 @@ export const getAllNamespaces = () =>
117
116
  data: europaValidData,
118
117
  };
119
118
  } catch (error) {
120
- logValidationError('EuropaSchema', error, { data });
119
+ log.error(error, { data });
121
120
  throw error;
122
121
  }
123
122
  }),
@@ -9,7 +9,7 @@ import {
9
9
  } from 'runtypes';
10
10
  import getOrUpdate from '../utils/getOrUpdate';
11
11
  import { UserAttributes } from '../types';
12
- import logValidationError from '../utils/logValidationError';
12
+ import log from '../utils/log';
13
13
 
14
14
  export type AccessFeatures = string[];
15
15
 
@@ -70,7 +70,7 @@ export const checkForAccess = (
70
70
  data,
71
71
  };
72
72
  } catch (error) {
73
- logValidationError('CheckAccessForPaperSchema', error, { json });
73
+ log.error(error, { json });
74
74
  throw error;
75
75
  }
76
76
  })
@@ -90,7 +90,7 @@ export const getUserAccess = (publicationDomain: string): Promise<GetVstoken> =>
90
90
  try {
91
91
  return GetVstokenSchema.check(json);
92
92
  } catch (error) {
93
- logValidationError('GetVstokenSchema', error, { json });
93
+ log.error(error, { json });
94
94
  throw error;
95
95
  }
96
96
  });
@@ -113,7 +113,7 @@ export const getNonUserAccess = (
113
113
  try {
114
114
  return GetNonUserAccessSchema.check(json);
115
115
  } catch (error) {
116
- logValidationError('GetNonUserAccessSchema', error, { json });
116
+ log.error(error, { json });
117
117
  throw error;
118
118
  }
119
119
  });
@@ -33,38 +33,58 @@ describe('Mercury backendlog', () => {
33
33
  });
34
34
 
35
35
  describe('activateSubscription()', () => {
36
- it('should throw error if user is deactivated', () => {
36
+ it('should throw error if user is deactivated', async () => {
37
37
  fetch.mockResponse(JSON.stringify({ status: 'user_deactivated' }), {
38
38
  status: 401,
39
39
  });
40
- expect(activateSubscription(['newspaper'])).rejects.toThrow(
40
+ await expect(activateSubscription(['newspaper'])).rejects.toThrow(
41
41
  UserDeactivatedError
42
42
  );
43
43
  });
44
44
 
45
- it('should return false if user not found', () => {
45
+ it('should return empty list if user not found', async () => {
46
46
  fetch.mockResponse(JSON.stringify({ status: 'whatever' }), {
47
47
  status: 401,
48
48
  });
49
- expect(activateSubscription(['newspaper'])).resolves.toBe(false);
49
+ await expect(activateSubscription(['newspaper'])).resolves.toEqual([]);
50
50
  });
51
51
 
52
- it('should return false if access is not "granted"', () => {
53
- fetch.mockResponse(JSON.stringify({ status: 'success', access: 'denied' }));
54
- expect(activateSubscription(['newspaper'])).resolves.toBe(false);
52
+ it('should return list if access features even if requested access is not "granted"', async () => {
53
+ fetch.mockResponse(
54
+ JSON.stringify({
55
+ status: 'success',
56
+ access: 'denied',
57
+ access_features: ['newspaper'],
58
+ })
59
+ );
60
+ await expect(activateSubscription(['newspaper'])).resolves.toEqual([
61
+ 'newspaper',
62
+ ]);
55
63
  });
56
64
 
57
- it('should return false if status is not "success"', () => {
65
+ it('should return list of access features even if status is not "success"', async () => {
58
66
  fetch.mockResponse(
59
- JSON.stringify({ status: 'unknown', access: 'granted' })
67
+ JSON.stringify({
68
+ status: 'unknown',
69
+ access: 'granted',
70
+ access_features: ['newspaper'],
71
+ })
60
72
  );
61
- expect(activateSubscription(['newspaper'])).resolves.toBe(false);
73
+ await expect(activateSubscription(['newspaper'])).resolves.toEqual([
74
+ 'newspaper',
75
+ ]);
62
76
  });
63
77
 
64
- it('should return true if status is "success" and access is "granted"', () => {
78
+ it('should return ["newspaper"] if status is "success" and access is "granted"', async () => {
65
79
  fetch.mockResponse(
66
- JSON.stringify({ status: 'success', access: 'granted' })
80
+ JSON.stringify({
81
+ status: 'success',
82
+ access: 'granted',
83
+ access_features: ['newspaper'],
84
+ })
67
85
  );
68
- expect(activateSubscription(['newspaper'])).resolves.toBe(true);
86
+ await expect(activateSubscription(['newspaper'])).resolves.toEqual([
87
+ 'newspaper',
88
+ ]);
69
89
  });
70
90
  });
@@ -11,7 +11,6 @@ function postLog(url: string, query: { [index: string]: any }) {
11
11
  method: 'POST',
12
12
  body,
13
13
  headers: {
14
- 'Content-Type': 'application/x-www-form-urlencoded',
15
14
  Accept: 'application/json',
16
15
  },
17
16
  };
@@ -22,28 +21,24 @@ function postLog(url: string, query: { [index: string]: any }) {
22
21
  });
23
22
  }
24
23
 
25
- const backendLog = (
26
- level: string,
27
- message: string,
28
- context: { [index: string]: any }
29
- ) => {
24
+ const backendLog = (level: string, message: string, context: Object) => {
30
25
  const extendedContext = {
31
26
  ...context,
32
27
  message,
33
28
  url: getCurrentUrl(),
34
29
  domain: getCurrentHostname(),
35
30
  };
36
- postLog(`//www.aid.no/api/mercury/v1/log/${level}`, extendedContext);
31
+ postLog(`/api/mercury/v1/log/${level}`, extendedContext);
37
32
  };
38
33
 
39
34
  const log = {
40
- error: (message: string, context: { [index: string]: any }) =>
35
+ error: (message: string, context: Object) =>
41
36
  backendLog('error', message, context),
42
- warn: (message: string, context: { [index: string]: any }) =>
37
+ warn: (message: string, context: Object) =>
43
38
  backendLog('warn', message, context),
44
- info: (message: string, context: { [index: string]: any }) =>
39
+ info: (message: string, context: Object) =>
45
40
  backendLog('info', message, context),
46
- debug: (message: string, context: { [index: string]: any }) =>
41
+ debug: (message: string, context: Object) =>
47
42
  backendLog('debug', message, context),
48
43
  };
49
44
 
@@ -51,7 +46,7 @@ export class UserDeactivatedError extends Error {}
51
46
 
52
47
  export const activateSubscription = async (
53
48
  accessFeatures: string[]
54
- ): Promise<boolean> =>
49
+ ): Promise<string[]> =>
55
50
  fetch(
56
51
  `/api/mercury/v2/access/activate?publication_wwwdomain=${getCurrentPublicationDomain()}&access_features=${accessFeatures.join(
57
52
  ','
@@ -64,15 +59,18 @@ export const activateSubscription = async (
64
59
  try {
65
60
  data = await response.json();
66
61
  } catch (error) {
67
- log.error('Body does not contain parsable json', error);
62
+ log.error(
63
+ 'Activate subscription. Response from mercury does not contain parsable json',
64
+ { error, response, accessFeatures }
65
+ );
68
66
  }
69
67
  if (!response.ok) {
70
68
  if (response.status === 401 && data?.status === 'user_deactivated') {
71
69
  throw new UserDeactivatedError();
72
70
  }
73
- return false;
71
+ return [];
74
72
  }
75
- return data?.status === 'success' && data?.access === 'granted';
73
+ return data?.access_features;
76
74
  });
77
75
 
78
76
  export default log;
@@ -9,7 +9,7 @@ import {
9
9
  } from 'runtypes';
10
10
  import getOrUpdate from '../utils/getOrUpdate';
11
11
  import { UserAttributes } from '../types';
12
- import logValidationError from '../utils/logValidationError';
12
+ import log from '../utils/log';
13
13
 
14
14
  const InfoSchema = Dictionary(Unknown, String).And(
15
15
  Partial({
@@ -61,7 +61,7 @@ const getNebulaData = (
61
61
  data: InfoSchema.check(json),
62
62
  };
63
63
  } catch (error) {
64
- logValidationError('InfoSchema', error, { json });
64
+ log.error(error, { json });
65
65
  throw error;
66
66
  }
67
67
  });
@@ -3,7 +3,6 @@ import log from '../utils/log';
3
3
  import getOrUpdate from '../utils/getOrUpdate';
4
4
  import store from '../store';
5
5
  import { UserAttributes } from '../types';
6
- import logValidationError from '../utils/logValidationError';
7
6
 
8
7
  const ServiceSessionSchema = Partial({
9
8
  user_uuid: String,
@@ -47,7 +46,7 @@ const fetchCurrentSession = () =>
47
46
  data: ServiceSessionSchema.check(json),
48
47
  };
49
48
  } catch (error) {
50
- logValidationError('ServiceSessionSchema', error, { json });
49
+ log.error(error, { json });
51
50
  return nodata;
52
51
  }
53
52
  });
@@ -12,17 +12,17 @@ declare global {
12
12
  accessFeatures: string[];
13
13
  }>;
14
14
  [ActivationEvents.ON_ACTIVATION_COMPLETE]: CustomEvent<{
15
- hasAccess: boolean;
15
+ accessFeatures: string[];
16
16
  }>;
17
17
  }
18
18
  }
19
19
 
20
20
  export const listenForActivationRequests = () => {
21
21
  listenWithExclusivity(ActivationEvents.REQUEST_ACTIVATION, (evt) => {
22
- activate(evt.detail.accessFeatures).then((result) => {
22
+ activate(evt.detail.accessFeatures).then((accessFeatures) => {
23
23
  dispatch(
24
24
  new CustomEvent(ActivationEvents.ON_ACTIVATION_COMPLETE, {
25
- detail: { hasAccess: result },
25
+ detail: { accessFeatures },
26
26
  })
27
27
  );
28
28
  });
package/src/index.ts CHANGED
@@ -1,21 +1,16 @@
1
1
  import { ActivationEvents } from './eventHandlers/activation';
2
2
  import { dispatch, listenForAllEvents } from './utils/customEventWrapper';
3
3
  import * as authentication from './actions/authentication';
4
- import UserDataRequest from './lib/UserDataRequest';
5
- import PaywallUnlockRequest from './lib/PaywallUnlockRequest';
6
4
  import { AmediaUserEvents } from './eventHandlers/eventMap';
7
5
  import { getCurrentUrl } from './utils/url';
8
6
  import { runJanitor } from './janitor';
9
7
  import { listenForStateRequests } from './eventHandlers/state';
10
8
  import { listenForUserAttributeRequests } from './eventHandlers/userAttributes';
11
9
  import { listenForStorageRequests } from './eventHandlers/storage';
10
+ import { hasAccess } from './actions/authorization';
12
11
 
13
- /**
14
- * Enables you to subscribe to the user attributes you care about and
15
- * get notified when something changes
16
- */
17
- export const user = () => new UserDataRequest();
18
- export const paywall = () => new PaywallUnlockRequest();
12
+ export { default as UserDataRequest } from './lib/UserDataRequest';
13
+ export { default as PaywallUnlockRequest } from './lib/PaywallUnlockRequest';
19
14
 
20
15
  /**
21
16
  * This will, if necessary, trigger a redirect to www.aid.no and return
@@ -28,15 +23,19 @@ export const goToLoginPage = (requestedUrl?: string) =>
28
23
  export const logout = () => authentication.logout();
29
24
 
30
25
  export const tryActivateSubscriptionAccess = (
31
- accessFeatures: string[]
32
- ): Promise<{ hasAccess: boolean }> =>
26
+ requestedAccessFeatures: string[]
27
+ ): Promise<{ hasAccess: boolean; accessFeatures: string[] }> =>
33
28
  new Promise((resolve) => {
34
- listenForAllEvents(ActivationEvents.ON_ACTIVATION_COMPLETE, (evt) =>
35
- resolve(evt.detail)
36
- );
29
+ listenForAllEvents(ActivationEvents.ON_ACTIVATION_COMPLETE, (evt) => {
30
+ const activatedAccessFeatures = evt.detail.accessFeatures;
31
+ resolve({
32
+ hasAccess: hasAccess(activatedAccessFeatures, requestedAccessFeatures),
33
+ accessFeatures: activatedAccessFeatures,
34
+ });
35
+ });
37
36
  dispatch(
38
37
  new CustomEvent(ActivationEvents.REQUEST_ACTIVATION, {
39
- detail: { accessFeatures },
38
+ detail: { accessFeatures: requestedAccessFeatures },
40
39
  })
41
40
  );
42
41
  });
@@ -158,7 +158,7 @@ describe('PaywallUnlocker', () => {
158
158
  success: true,
159
159
  accessFeatures: ['newspaper'],
160
160
  });
161
- spyOn(authorization, 'activate').mockResolvedValue(true);
161
+ spyOn(authorization, 'activate').mockResolvedValue(['newspaper']);
162
162
  });
163
163
 
164
164
  describe('with no post access actions', () => {
@@ -235,7 +235,7 @@ describe('PaywallUnlocker', () => {
235
235
  success: true,
236
236
  accessFeatures: [],
237
237
  });
238
- spyOn(authorization, 'activate').mockResolvedValue(false);
238
+ spyOn(authorization, 'activate').mockResolvedValue([]);
239
239
  unlockResponse = await new PaywallUnlockRequest().tryUnlock();
240
240
  });
241
241
 
@@ -259,7 +259,7 @@ describe('PaywallUnlocker', () => {
259
259
  success: true,
260
260
  accessFeatures: ['newspaper'],
261
261
  });
262
- spyOn(authorization, 'activate').mockResolvedValue(false);
262
+ spyOn(authorization, 'activate').mockResolvedValue(['newspaper']);
263
263
  unlockResponse = await new PaywallUnlockRequest()
264
264
  .withAccessFeatures(['plussalt'])
265
265
  .tryUnlock();
@@ -319,7 +319,10 @@ describe('PaywallUnlocker', () => {
319
319
  success: true,
320
320
  accessFeatures: ['newspaper'], // Notice not changed
321
321
  });
322
- spyOn(authorization, 'activate').mockResolvedValue(true);
322
+ spyOn(authorization, 'activate').mockResolvedValue([
323
+ 'newspaper',
324
+ 'plussalt',
325
+ ]);
323
326
  try {
324
327
  await new PaywallUnlockRequest()
325
328
  .withAccessFeatures(['plussalt'])
@@ -62,34 +62,30 @@ class PaywallUnlockRequest {
62
62
  };
63
63
  }
64
64
 
65
- let accessFeatures = await this.setAccessCookiesAndGetAccessFeatures();
66
- if (!hasAccess(accessFeatures, this.requestedAccessFeatures)) {
67
- /**
68
- * TODO: This introduces a bug for plussalt where a new user won't get access features, since activation fails.
69
- * TODO: The user should get {
70
- * isLoggedIn: true,
71
- * hasAccess: false,
72
- * accessFeatures: ['newspaper'],
73
- * }
74
- * TODO: The solution will be that activate returns access features as well after checking so we can return them.
75
- */
65
+ let currentAccess = await this.setAccessCookiesAndGetAccessFeatures(
66
+ this.requestedAccessFeatures
67
+ );
68
+ if (currentAccess.denied) {
76
69
  // Check if we actually have a valid subscription that's not properly connected to the user yet
77
- if (await activate(this.requestedAccessFeatures)) {
78
- accessFeatures = await this.setAccessCookiesAndGetAccessFeatures();
79
- if (!hasAccess(accessFeatures, this.requestedAccessFeatures)) {
80
- throw new PaywallError(
81
- 'New subscription was attached and checked successfully, but internal systems disagree about current newspaper access.',
82
- PaywallError.ERROR_NO_ACCESS_AFTER_SUCCESSFUL_ACTIVATION_WITH_REQUESTED_ACCESS_FEATURES
83
- );
84
- }
85
- } else {
70
+ currentAccess = await this.activateAccess(this.requestedAccessFeatures);
71
+ if (currentAccess.denied) {
86
72
  return {
87
73
  isLoggedIn: true,
88
74
  hasAccess: false,
89
- accessFeatures,
75
+ accessFeatures: currentAccess.accessFeatures,
90
76
  };
91
77
  }
78
+ currentAccess = await this.setAccessCookiesAndGetAccessFeatures(
79
+ this.requestedAccessFeatures
80
+ );
81
+ if (currentAccess.denied) {
82
+ throw new PaywallError(
83
+ 'New subscription was attached and checked successfully, but internal systems disagree about current newspaper access.',
84
+ PaywallError.ERROR_NO_ACCESS_AFTER_SUCCESSFUL_ACTIVATION_WITH_REQUESTED_ACCESS_FEATURES
85
+ );
86
+ }
92
87
  }
88
+ setHasTriedToUnlockPaywall();
93
89
  if (this.reload) {
94
90
  location.reload();
95
91
  }
@@ -99,23 +95,37 @@ class PaywallUnlockRequest {
99
95
  return {
100
96
  isLoggedIn: true,
101
97
  hasAccess: true,
102
- accessFeatures,
98
+ accessFeatures: currentAccess.accessFeatures,
103
99
  };
104
100
  }
105
101
 
106
102
  // eslint-disable-next-line class-methods-use-this
107
- private setAccessCookiesAndGetAccessFeatures() {
103
+ private setAccessCookiesAndGetAccessFeatures(requestedAccessFeatures) {
108
104
  return setAccessCookies(getCurrentPublicationDomain()).then((response) => {
109
- if (!response.success) {
105
+ const accessDenied = !hasAccess(
106
+ response.accessFeatures,
107
+ requestedAccessFeatures
108
+ );
109
+ if (!response.success && accessDenied) {
110
110
  throw new PaywallError(
111
111
  'Could not set access cookies',
112
112
  PaywallError.ERROR_ENABLING_ACCESS_FAILED
113
113
  );
114
114
  }
115
- setHasTriedToUnlockPaywall();
116
- return response.accessFeatures;
115
+ return {
116
+ denied: accessDenied,
117
+ accessFeatures: response.accessFeatures,
118
+ };
117
119
  });
118
120
  }
121
+
122
+ private async activateAccess(requestedAccessFeatures) {
123
+ const accessFeatures = await activate(this.requestedAccessFeatures);
124
+ return {
125
+ denied: !hasAccess(accessFeatures, requestedAccessFeatures),
126
+ accessFeatures,
127
+ };
128
+ }
119
129
  }
120
130
 
121
131
  export default PaywallUnlockRequest;