@amedia/user 0.14.6 → 0.14.8-111

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.
package/README.md CHANGED
@@ -29,7 +29,7 @@ You can read more about Eik on [Slite](https://amedia.slite.com/app/channels/hOl
29
29
  ## Contributing to @amedia/user
30
30
  Hey, thanks! :)
31
31
 
32
- It's often nice to do development while testing on a real app. You may do so using `npm link`. When you run then `npm run build` this will expose actual code, letting you develop faster. This is because we still export user.js from the package, but replaces it content with an error if used directly.
32
+ It's often nice to do development while testing on a real app. You may do so using `npm link`. When you run then `npm run build` (or `npm run dev` if you want to watch for changes and build automatically) this will expose actual code, letting you develop faster. This is because we still export user.js from the package, but replaces it content with an error if used directly.
33
33
 
34
34
  PS: Remember to comment-out the module in import maps ;-)
35
35
 
@@ -151,6 +151,7 @@ To unlock the paywall, you first need to create a new `PaywallUnlockRequest`. On
151
151
  to `requestedUrl`. (Provides more flexibility than `reloadOnAccess()`)
152
152
  - `withAccessFeatures(accessFeatures: string[])`: Specify what access features will give access to the current content.
153
153
  The default is [`newspaper`].
154
+ - `withPublicationDomain(domain: string)`: Specify which site we to attempt activation against. The default is the current domain. This is mostly useful for direktesport.no which often knows what domain the user came from.
154
155
 
155
156
  More details about the access model can be found here: [Access model](https://amedia.slite.com/app/channels/hOlqx3Miez/notes/nhG2Ok39BN)
156
157
 
package/dist/user.d.ts CHANGED
@@ -16,7 +16,7 @@ declare module '@amedia/user/actions/authorization' {
16
16
  accessFeatures: string[];
17
17
  };
18
18
  export const getAccess: (accessFeatures?: string[]) => Promise<Pick<UserAttributes, 'access'>>;
19
- export const activate: (accessFeatures: string[]) => Promise<string[]>;
19
+ export const activate: (accessFeatures: string[], publicationDomain: string) => Promise<string[]>;
20
20
  export const hasAccess: (currentAccessFeatures: string[], requestedAccessFeatures: string[]) => boolean;
21
21
  export const setUserAccessCookie: (publicationDomain: string) => Promise<SetCookieResponse>;
22
22
  export const setNonUserAccessCookie: (publicationDomain: string) => Promise<SetCookieResponse>;
@@ -206,6 +206,15 @@ declare module '@amedia/user/clients/jupiter' {
206
206
  access_features: Array<String, false>;
207
207
  }, false>;
208
208
  export type GetVstoken = Static<typeof GetVstokenSchema>;
209
+ const SitesSchema: Array<Record<{
210
+ key: String;
211
+ domain: String;
212
+ name: Record<{
213
+ full: String;
214
+ short: String;
215
+ }, false>;
216
+ }, false>, false>;
217
+ export type Sites = Static<typeof SitesSchema>;
209
218
  const GetNonUserAccessSchema: Record<{
210
219
  status: Literal<"success">;
211
220
  vstoken_cookie: String;
@@ -215,6 +224,11 @@ declare module '@amedia/user/clients/jupiter' {
215
224
  export type GetNonUserAccess = Static<typeof GetNonUserAccessSchema>;
216
225
  export const checkForAccess: (publicationDomain: string, accessFeatures: AccessFeatures) => Promise<Pick<UserAttributes, 'access'>>;
217
226
  export const getUserAccess: (publicationDomain: string) => Promise<GetVstoken>;
227
+ export const getSitesWithAccessFeatures: ({ accessFeatures, excludeBundles, sortBy, }: {
228
+ accessFeatures: string[];
229
+ excludeBundles?: boolean | undefined;
230
+ sortBy?: "domain" | "veiklasse" | undefined;
231
+ }) => Promise<Sites>;
218
232
  export const getNonUserAccess: (publicationDomain: string) => Promise<GetNonUserAccess>;
219
233
  export {};
220
234
 
@@ -226,7 +240,7 @@ declare module '@amedia/user/clients/jupiter.spec' {
226
240
  declare module '@amedia/user/clients/mercury' {
227
241
  export class UserDeactivatedError extends Error {
228
242
  }
229
- export const activateSubscription: (accessFeatures: string[]) => Promise<string[]>;
243
+ export const activateSubscription: (accessFeatures: string[], publicationDomain: string) => Promise<string[]>;
230
244
 
231
245
  }
232
246
  declare module '@amedia/user/clients/mercury.spec' {
@@ -277,6 +291,7 @@ declare module '@amedia/user/eventHandlers/activation' {
277
291
  interface WindowEventMap {
278
292
  [ActivationEvents.REQUEST_ACTIVATION]: CustomEvent<{
279
293
  accessFeatures: string[];
294
+ publicationDomain?: string;
280
295
  }>;
281
296
  [ActivationEvents.ON_ACTIVATION_COMPLETE]: CustomEvent<{
282
297
  accessFeatures: string[];
@@ -456,15 +471,24 @@ declare module '@amedia/user/janitor/jobs/removeUserStorage.spec' {
456
471
 
457
472
  }
458
473
  declare module '@amedia/user/lib/PaywallUnlockRequest' {
474
+ export enum AffiliationType {
475
+ ACCESS = "access"
476
+ }
459
477
  export type UnlockResponse = {
460
478
  isLoggedIn: boolean;
461
479
  hasAccess: boolean;
480
+ primarySite?: null | {
481
+ domain: string;
482
+ affiliation: AffiliationType;
483
+ };
462
484
  accessFeatures: string[];
463
485
  };
464
486
  class PaywallUnlockRequest {
465
487
  private requestedAccessFeatures;
466
488
  private reload;
467
489
  private requestedUrl;
490
+ private publicationDomain;
491
+ withPublicationDomain(publicationDomain: string): this;
468
492
  withAccessFeatures(accessFeatures: string[]): this;
469
493
  reloadOnAccess(): this;
470
494
  redirectOnAccess(requestedUrl: string): this;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amedia/user",
3
- "version": "0.14.6",
3
+ "version": "0.14.8-111",
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)",
@@ -21,6 +21,7 @@
21
21
  "clean-dist": "rm -rf ./dist",
22
22
  "lint": "eslint ./src --ext .ts",
23
23
  "build": "npm install && node build.js",
24
+ "dev": "node build.js --watch",
24
25
  "typings": "tsc --noEmit",
25
26
  "checkVersion": "node --experimental-json-modules checkVersion.js",
26
27
  "stub-npmjs-package": "find ./dist -type f ! -name '*.d.ts' -delete && cp -v stubs/* dist/.",
@@ -20,6 +20,7 @@ export const login = (requestedUrl: URL | string) => {
20
20
 
21
21
  function clearCookies() {
22
22
  removeCookie('VSTOKEN');
23
+ removeCookie('VSTOKEN2');
23
24
  removeCookie('aid.session');
24
25
  removeCookie('aid_invitation_code');
25
26
  removeCookie('aid-reload-article');
@@ -49,8 +49,13 @@ describe('activate', () => {
49
49
  .mockResolvedValue(['whatever']);
50
50
  });
51
51
  it('Returns whatever mercury returns', async () => {
52
- expect(await activate(['newspaper'])).toEqual(['whatever']);
53
- expect(mercury.activateSubscription).toHaveBeenCalledWith(['newspaper']);
52
+ expect(await activate(['newspaper'], 'www.telen.no')).toEqual([
53
+ 'whatever',
54
+ ]);
55
+ expect(mercury.activateSubscription).toHaveBeenCalledWith(
56
+ ['newspaper'],
57
+ 'www.telen.no'
58
+ );
54
59
  });
55
60
  });
56
61
 
@@ -62,8 +67,11 @@ describe('activate', () => {
62
67
  jest.spyOn(authentication, 'logout').mockResolvedValue(undefined);
63
68
  });
64
69
  it('Returns whatever mercury returns', async () => {
65
- expect(await activate([])).toEqual([]);
66
- expect(mercury.activateSubscription).toHaveBeenCalledWith([]);
70
+ expect(await activate([], 'www.telen.no')).toEqual([]);
71
+ expect(mercury.activateSubscription).toHaveBeenCalledWith(
72
+ [],
73
+ 'www.telen.no'
74
+ );
67
75
  expect(authentication.logout).toHaveBeenCalled();
68
76
  });
69
77
  });
@@ -16,9 +16,12 @@ export const getAccess = (
16
16
  ): Promise<Pick<UserAttributes, 'access'>> =>
17
17
  checkForAccess(getCurrentPublicationDomain(), accessFeatures);
18
18
 
19
- export const activate = async (accessFeatures: string[]): Promise<string[]> => {
19
+ export const activate = async (
20
+ accessFeatures: string[],
21
+ publicationDomain: string
22
+ ): Promise<string[]> => {
20
23
  try {
21
- return await activateSubscription(accessFeatures);
24
+ return await activateSubscription(accessFeatures, publicationDomain);
22
25
  } catch (error) {
23
26
  if (error instanceof UserDeactivatedError) {
24
27
  await logout();
@@ -1,4 +1,5 @@
1
1
  import fetch from 'jest-fetch-mock';
2
+ import { ValidationError } from 'runtypes';
2
3
  import cache from '../cache';
3
4
  import log from '../utils/log';
4
5
  import {
@@ -9,8 +10,10 @@ import {
9
10
  GetVstoken,
10
11
  GetNonUserAccess,
11
12
  getNonUserAccess,
13
+ getSitesWithAccessFeatures,
12
14
  } from './jupiter';
13
15
  import anything = jasmine.anything;
16
+ import spyOn = jest.spyOn;
14
17
 
15
18
  beforeEach(async () => {
16
19
  await cache.clear();
@@ -176,4 +179,74 @@ describe('jupiter service', () => {
176
179
  );
177
180
  });
178
181
  });
182
+
183
+ describe('GET /sites_with_access_features', () => {
184
+ describe('with bad response', () => {
185
+ beforeEach(() => {
186
+ fetch.mockResponseOnce(JSON.stringify({ status: 'no_session_found' }), {
187
+ status: 400,
188
+ });
189
+ });
190
+
191
+ it('should throw error', async () => {
192
+ await expect(
193
+ getSitesWithAccessFeatures({ accessFeatures: ['newspaper'] })
194
+ ).rejects.toThrow('Request not ok (400: Bad Request).');
195
+ });
196
+ });
197
+
198
+ describe('with invalid schema', () => {
199
+ beforeEach(() => {
200
+ log.error = jest.fn();
201
+ fetch.mockResponseOnce(JSON.stringify([{ invalid: 'schema' }]));
202
+ });
203
+
204
+ it('should throw error', async () => {
205
+ await expect(
206
+ getSitesWithAccessFeatures({
207
+ accessFeatures: ['newspaper'],
208
+ excludeBundles: true,
209
+ })
210
+ ).rejects.toThrow(
211
+ 'Expected { key: string; domain: string; name: { full: string; short: string; }; }[], but was incompatible'
212
+ );
213
+ expect(log.error).toHaveBeenCalledWith(jasmine.any(ValidationError), {
214
+ json: [{ invalid: 'schema' }],
215
+ });
216
+ });
217
+ });
218
+
219
+ describe('with valid data', () => {
220
+ beforeEach(() => {
221
+ log.error = jest.fn();
222
+ fetch.mockResponseOnce(
223
+ JSON.stringify([
224
+ {
225
+ key: 'telen__',
226
+ name: {
227
+ full: 'Telen',
228
+ short: 'Telen',
229
+ },
230
+ domain: 'www.telen.no',
231
+ },
232
+ ])
233
+ );
234
+ });
235
+
236
+ it('should return expected', async () => {
237
+ await expect(
238
+ getSitesWithAccessFeatures({ accessFeatures: ['newspaper'] })
239
+ ).resolves.toEqual([
240
+ {
241
+ key: 'telen__',
242
+ name: {
243
+ full: 'Telen',
244
+ short: 'Telen',
245
+ },
246
+ domain: 'www.telen.no',
247
+ },
248
+ ]);
249
+ });
250
+ });
251
+ });
179
252
  });
@@ -34,6 +34,19 @@ const GetVstokenSchema = Record({
34
34
 
35
35
  export type GetVstoken = Static<typeof GetVstokenSchema>;
36
36
 
37
+ const SitesSchema = Array(
38
+ Record({
39
+ key: String,
40
+ domain: String,
41
+ name: Record({
42
+ full: String,
43
+ short: String,
44
+ }),
45
+ })
46
+ );
47
+
48
+ export type Sites = Static<typeof SitesSchema>;
49
+
37
50
  const GetNonUserAccessSchema = Record({
38
51
  status: Literal('success'),
39
52
  vstoken_cookie: String,
@@ -95,6 +108,42 @@ export const getUserAccess = (publicationDomain: string): Promise<GetVstoken> =>
95
108
  }
96
109
  });
97
110
 
111
+ export const getSitesWithAccessFeatures = ({
112
+ accessFeatures,
113
+ excludeBundles,
114
+ sortBy = 'domain',
115
+ }: {
116
+ accessFeatures: string[];
117
+ excludeBundles?: boolean;
118
+ sortBy?: 'domain' | 'veiklasse';
119
+ }): Promise<Sites> =>
120
+ fetch(
121
+ `/api/jupiter/v1/sites_with_access_features?${new URLSearchParams({
122
+ access_features: accessFeatures.join(','),
123
+ exclude_bundles: excludeBundles ? 'true' : 'false',
124
+ sort_by: sortBy,
125
+ })}`,
126
+ {
127
+ method: 'get',
128
+ }
129
+ )
130
+ .then((response) => {
131
+ if (!response.ok) {
132
+ throw new Error(
133
+ `Request not ok (${response.status}: ${response.statusText}).`
134
+ );
135
+ }
136
+ return response.json();
137
+ })
138
+ .then((json) => {
139
+ try {
140
+ return SitesSchema.check(json);
141
+ } catch (error) {
142
+ log.error(error, { json });
143
+ throw error;
144
+ }
145
+ });
146
+
98
147
  export const getNonUserAccess = (
99
148
  publicationDomain: string
100
149
  ): Promise<GetNonUserAccess> =>
@@ -6,16 +6,18 @@ describe('activateSubscription()', () => {
6
6
  fetch.mockResponse(JSON.stringify({ status: 'user_deactivated' }), {
7
7
  status: 401,
8
8
  });
9
- await expect(activateSubscription(['newspaper'])).rejects.toThrow(
10
- UserDeactivatedError
11
- );
9
+ await expect(
10
+ activateSubscription(['newspaper'], 'www.telen.no')
11
+ ).rejects.toThrow(UserDeactivatedError);
12
12
  });
13
13
 
14
14
  it('should return empty list if user not found', async () => {
15
15
  fetch.mockResponse(JSON.stringify({ status: 'no_session_found' }), {
16
16
  status: 401,
17
17
  });
18
- await expect(activateSubscription(['newspaper'])).resolves.toEqual([]);
18
+ await expect(
19
+ activateSubscription(['newspaper'], 'www.telen.no')
20
+ ).resolves.toEqual([]);
19
21
  });
20
22
 
21
23
  it('should return list if access features even if requested access is not "granted"', async () => {
@@ -26,9 +28,9 @@ describe('activateSubscription()', () => {
26
28
  access_features: ['newspaper'],
27
29
  })
28
30
  );
29
- await expect(activateSubscription(['newspaper'])).resolves.toEqual([
30
- 'newspaper',
31
- ]);
31
+ await expect(
32
+ activateSubscription(['newspaper'], 'www.telen.no')
33
+ ).resolves.toEqual(['newspaper']);
32
34
  });
33
35
 
34
36
  it('should return list of access features even if status is not "success"', async () => {
@@ -39,9 +41,9 @@ describe('activateSubscription()', () => {
39
41
  access_features: ['newspaper'],
40
42
  })
41
43
  );
42
- await expect(activateSubscription(['newspaper'])).resolves.toEqual([
43
- 'newspaper',
44
- ]);
44
+ await expect(
45
+ activateSubscription(['newspaper'], 'www.telen.no')
46
+ ).resolves.toEqual(['newspaper']);
45
47
  });
46
48
 
47
49
  it('should return ["newspaper"] if status is "success" and access is "granted"', async () => {
@@ -52,8 +54,8 @@ describe('activateSubscription()', () => {
52
54
  access_features: ['newspaper'],
53
55
  })
54
56
  );
55
- await expect(activateSubscription(['newspaper'])).resolves.toEqual([
56
- 'newspaper',
57
- ]);
57
+ await expect(
58
+ activateSubscription(['newspaper'], 'www.telen.no')
59
+ ).resolves.toEqual(['newspaper']);
58
60
  });
59
61
  });
@@ -1,5 +1,4 @@
1
1
  import log from '../utils/log';
2
- import { getCurrentPublicationDomain } from '../utils/url';
3
2
 
4
3
  export class UserDeactivatedError extends Error {}
5
4
 
@@ -10,10 +9,11 @@ const EXPECTED_ERRORS = [
10
9
  ];
11
10
 
12
11
  export const activateSubscription = async (
13
- accessFeatures: string[]
12
+ accessFeatures: string[],
13
+ publicationDomain: string
14
14
  ): Promise<string[]> =>
15
15
  fetch(
16
- `/api/mercury/v2/access/activate?publication_wwwdomain=${getCurrentPublicationDomain()}&access_features=${accessFeatures.join(
16
+ `/api/mercury/v2/access/activate?publication_wwwdomain=${publicationDomain}&access_features=${accessFeatures.join(
17
17
  ','
18
18
  )}`,
19
19
  {
@@ -1,6 +1,7 @@
1
1
  import { dispatch, listenWithExclusivity } from '../utils/customEventWrapper';
2
2
  import { activate } from '../actions/authorization';
3
3
  import getGlobalThis from '../utils/getGlobalThis';
4
+ import { getCurrentPublicationDomain } from '../utils/url';
4
5
 
5
6
  export enum ActivationEvents {
6
7
  REQUEST_ACTIVATION = 'amedia-user.activation.request-activation',
@@ -11,6 +12,7 @@ declare global {
11
12
  interface WindowEventMap {
12
13
  [ActivationEvents.REQUEST_ACTIVATION]: CustomEvent<{
13
14
  accessFeatures: string[];
15
+ publicationDomain?: string;
14
16
  }>;
15
17
  [ActivationEvents.ON_ACTIVATION_COMPLETE]: CustomEvent<{
16
18
  accessFeatures: string[];
@@ -20,7 +22,10 @@ declare global {
20
22
 
21
23
  export const listenForActivationRequests = () => {
22
24
  listenWithExclusivity(ActivationEvents.REQUEST_ACTIVATION, (evt) => {
23
- activate(evt.detail.accessFeatures).then((accessFeatures) => {
25
+ activate(
26
+ evt.detail.accessFeatures,
27
+ evt.detail.publicationDomain || getCurrentPublicationDomain()
28
+ ).then((accessFeatures) => {
24
29
  dispatch(
25
30
  new CustomEvent(ActivationEvents.ON_ACTIVATION_COMPLETE, {
26
31
  detail: { accessFeatures },
@@ -201,12 +201,12 @@ describe('accessCookieRefresher', () => {
201
201
  );
202
202
  jest.spyOn(cookie, 'removeCookie').mockImplementation();
203
203
  });
204
- it('Should remove user access cookie', async () => {
204
+ it('Should remove user access cookie, but not VSTOKEN2 (keep for Nasjonal avisuke)', async () => {
205
205
  expect(await accessCookieRefresher()).toEqual([undefined, undefined]);
206
206
  expect(authorization.setUserAccessCookie).toHaveBeenCalledTimes(0);
207
207
  expect(authorization.setNonUserAccessCookie).toHaveBeenCalledTimes(0);
208
+ expect(cookie.removeCookie).toHaveBeenCalledTimes(1);
208
209
  expect(cookie.removeCookie).toHaveBeenNthCalledWith(1, 'VSTOKEN');
209
- expect(cookie.removeCookie).toHaveBeenNthCalledWith(2, 'VSTOKEN2');
210
210
  });
211
211
  });
212
212
  });
@@ -83,8 +83,6 @@ function verifyAndSetNonUserAccessCookie() {
83
83
  return;
84
84
  }
85
85
  await setNonUserAccessCookie(publicationDomain);
86
- } else {
87
- removeCookie(cookieName);
88
86
  }
89
87
  })
90
88
  .then(() => {});
@@ -1,8 +1,12 @@
1
- import PaywallUnlockRequest, { UnlockResponse } from './PaywallUnlockRequest';
1
+ import PaywallUnlockRequest, {
2
+ AffiliationType,
3
+ UnlockResponse,
4
+ } from './PaywallUnlockRequest';
2
5
  import * as authorization from '../actions/authorization';
3
6
  import * as location from '../utils/location';
4
7
  import * as autologin from '../autologin';
5
8
  import * as localhostCheck from '../utils/localhostCheck';
9
+ import * as jupiter from '../clients/jupiter';
6
10
  import store from '../store';
7
11
  import PaywallError from '../exceptions/PaywallError';
8
12
  import { listenForUserAttributeRequests } from '../eventHandlers/userAttributes';
@@ -37,9 +41,27 @@ function itShouldNotAttemptActivation() {
37
41
  });
38
42
  }
39
43
 
40
- function itShouldAttemptActivationWithAccessFeatures(accessFeatures: string[]) {
44
+ function itShouldAttemptActivationWithAccessFeatures(
45
+ accessFeatures: string[],
46
+ publicationDomain: string = 'localhost'
47
+ ) {
41
48
  it('should attempt activation with access features', () => {
42
- expect(authorization.activate).toHaveBeenCalledWith(accessFeatures);
49
+ expect(authorization.activate).toHaveBeenCalledWith(
50
+ accessFeatures,
51
+ publicationDomain
52
+ );
53
+ });
54
+ }
55
+
56
+ function itShouldHaveAskedForSitesThatProvideRequestedAccessFeatures(
57
+ accessFeatures: string[]
58
+ ) {
59
+ it('should have asked for sites', () => {
60
+ expect(jupiter.getSitesWithAccessFeatures).toHaveBeenCalledWith({
61
+ accessFeatures,
62
+ excludeBundles: true,
63
+ sortBy: 'veiklasse',
64
+ });
43
65
  });
44
66
  }
45
67
 
@@ -160,7 +182,7 @@ describe('PaywallUnlocker', () => {
160
182
  itShouldNotReload();
161
183
  });
162
184
 
163
- describe('when no access', () => {
185
+ describe('without access', () => {
164
186
  describe('and activation give access', () => {
165
187
  let unlockResponse: UnlockResponse;
166
188
  beforeEach(() => {
@@ -241,6 +263,29 @@ describe('PaywallUnlocker', () => {
241
263
  itShouldAttemptActivationWithAccessFeatures(['newspaper']);
242
264
  itShouldNotRedirect();
243
265
  });
266
+
267
+ describe('with specific publicationDomain', () => {
268
+ beforeEach(async () => {
269
+ unlockResponse = await new PaywallUnlockRequest()
270
+ .withPublicationDomain('www.telen.no')
271
+ .tryUnlock();
272
+ });
273
+
274
+ it('should give access with access features', () => {
275
+ expect(unlockResponse).toEqual({
276
+ isLoggedIn: true,
277
+ hasAccess: true,
278
+ accessFeatures: ['newspaper'],
279
+ });
280
+ });
281
+
282
+ itShouldAttemptActivationWithAccessFeatures(
283
+ ['newspaper'],
284
+ 'www.telen.no'
285
+ );
286
+ itShouldNotReload();
287
+ itShouldNotRedirect();
288
+ });
244
289
  });
245
290
 
246
291
  describe('and activation does not give access', () => {
@@ -251,6 +296,13 @@ describe('PaywallUnlocker', () => {
251
296
  accessFeatures: [],
252
297
  });
253
298
  spyOn(authorization, 'activate').mockResolvedValue([]);
299
+ spyOn(jupiter, 'getSitesWithAccessFeatures').mockResolvedValue([
300
+ {
301
+ key: 'telen__',
302
+ domain: 'www.telen.no',
303
+ name: { full: 'Telen', short: 'Telen' },
304
+ },
305
+ ]);
254
306
  unlockResponse = await new PaywallUnlockRequest().tryUnlock();
255
307
  });
256
308
 
@@ -259,9 +311,17 @@ describe('PaywallUnlocker', () => {
259
311
  isLoggedIn: true,
260
312
  hasAccess: false,
261
313
  accessFeatures: [],
314
+ primarySite: {
315
+ name: 'Telen',
316
+ domain: 'www.telen.no',
317
+ affiliation: AffiliationType.ACCESS,
318
+ },
262
319
  });
263
320
  });
264
321
 
322
+ itShouldHaveAskedForSitesThatProvideRequestedAccessFeatures([
323
+ 'newspaper',
324
+ ]);
265
325
  itShouldAttemptActivationWithAccessFeatures(['newspaper']);
266
326
  itShouldNotRedirect();
267
327
  itShouldNotReload();
@@ -275,6 +335,7 @@ describe('PaywallUnlocker', () => {
275
335
  accessFeatures: ['newspaper'],
276
336
  });
277
337
  spyOn(authorization, 'activate').mockResolvedValue(['newspaper']);
338
+ spyOn(jupiter, 'getSitesWithAccessFeatures').mockResolvedValue([]);
278
339
  unlockResponse = await new PaywallUnlockRequest()
279
340
  .withAccessFeatures(['plussalt'])
280
341
  .tryUnlock();
@@ -285,9 +346,13 @@ describe('PaywallUnlocker', () => {
285
346
  isLoggedIn: true,
286
347
  hasAccess: false,
287
348
  accessFeatures: ['newspaper'],
349
+ primarySite: null,
288
350
  });
289
351
  });
290
352
 
353
+ itShouldHaveAskedForSitesThatProvideRequestedAccessFeatures([
354
+ 'plussalt',
355
+ ]);
291
356
  itShouldAttemptActivationWithAccessFeatures(['plussalt']);
292
357
  itShouldNotRedirect();
293
358
  itShouldNotReload();
@@ -10,15 +10,39 @@ import * as location from '../utils/location';
10
10
  import PaywallError from '../exceptions/PaywallError';
11
11
  import UserDataRequest from './UserDataRequest';
12
12
  import { attemptPaywallAutoLogin } from '../autologin';
13
- import { AccessFeatures } from '../clients/jupiter';
13
+ import { AccessFeatures, getSitesWithAccessFeatures } from '../clients/jupiter';
14
14
  import { isRunningOnLocalhost } from '../utils/localhostCheck';
15
15
 
16
+ export enum AffiliationType {
17
+ ACCESS = 'access',
18
+ }
19
+
16
20
  export type UnlockResponse = {
17
21
  isLoggedIn: boolean;
18
22
  hasAccess: boolean;
23
+ primarySite?: null | { domain: string; affiliation: AffiliationType };
19
24
  accessFeatures: string[];
20
25
  };
21
26
 
27
+ async function getPrimarySite(accessFeatures: string[]) {
28
+ // This is where we should have called aid-subscription to get the user's subscriptions, but until
29
+ // this is ready, we only get sites the user has acces to, and choose one of those.
30
+ const sites = await getSitesWithAccessFeatures({
31
+ accessFeatures,
32
+ excludeBundles: true,
33
+ sortBy: 'veiklasse',
34
+ });
35
+ if (sites.length > 0) {
36
+ const site = sites[0];
37
+ return {
38
+ domain: site.domain,
39
+ name: site.name.full,
40
+ affiliation: AffiliationType.ACCESS,
41
+ };
42
+ }
43
+ return null;
44
+ }
45
+
22
46
  class PaywallUnlockRequest {
23
47
  private requestedAccessFeatures: string[] = ['newspaper'];
24
48
 
@@ -26,6 +50,13 @@ class PaywallUnlockRequest {
26
50
 
27
51
  private requestedUrl: string | undefined;
28
52
 
53
+ private publicationDomain: string = getCurrentPublicationDomain();
54
+
55
+ public withPublicationDomain(publicationDomain: string): this {
56
+ this.publicationDomain = publicationDomain;
57
+ return this;
58
+ }
59
+
29
60
  public withAccessFeatures(accessFeatures: string[]): this {
30
61
  this.requestedAccessFeatures = accessFeatures;
31
62
  return this;
@@ -68,9 +99,11 @@ class PaywallUnlockRequest {
68
99
  // Check if we actually have a valid subscription that's not properly connected to the user yet
69
100
  currentAccess = await this.activateAccess(this.requestedAccessFeatures);
70
101
  if (currentAccess.denied) {
102
+ const primarySite = await getPrimarySite(this.requestedAccessFeatures);
71
103
  return {
72
104
  isLoggedIn: true,
73
105
  hasAccess: false,
106
+ primarySite,
74
107
  accessFeatures: currentAccess.accessFeatures,
75
108
  };
76
109
  }
@@ -132,7 +165,10 @@ class PaywallUnlockRequest {
132
165
  }
133
166
 
134
167
  private async activateAccess(requestedAccessFeatures: AccessFeatures) {
135
- const accessFeatures = await activate(this.requestedAccessFeatures);
168
+ const accessFeatures = await activate(
169
+ this.requestedAccessFeatures,
170
+ this.publicationDomain
171
+ );
136
172
  return {
137
173
  denied: !hasAccess(accessFeatures, requestedAccessFeatures),
138
174
  accessFeatures,