@amedia/user 0.14.16 → 0.14.18

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/dist/user.d.ts CHANGED
@@ -207,15 +207,6 @@ declare module '@amedia/user/clients/jupiter' {
207
207
  access_features: Array<String, false>;
208
208
  }, false>;
209
209
  export type GetVstoken = Static<typeof GetVstokenSchema>;
210
- const SitesSchema: Array<Record<{
211
- key: String;
212
- domain: String;
213
- name: Record<{
214
- full: String;
215
- short: String;
216
- }, false>;
217
- }, false>, false>;
218
- export type Sites = Static<typeof SitesSchema>;
219
210
  const GetNonUserAccessSchema: Record<{
220
211
  status: Literal<"success">;
221
212
  vstoken_cookie: String;
@@ -225,11 +216,6 @@ declare module '@amedia/user/clients/jupiter' {
225
216
  export type GetNonUserAccess = Static<typeof GetNonUserAccessSchema>;
226
217
  export const checkForAccess: (siteDomain: string, accessFeatures: AccessFeatures) => Promise<Pick<UserAttributes, 'access'>>;
227
218
  export const getUserAccess: (siteDomain: string) => Promise<GetVstoken>;
228
- export const getSitesWithAccessFeatures: ({ accessFeatures, excludeBundles, sortBy, }: {
229
- accessFeatures: string[];
230
- excludeBundles?: boolean | undefined;
231
- sortBy?: "domain" | "veiklasse" | undefined;
232
- }) => Promise<Sites>;
233
219
  export const getNonUserAccess: (siteDomain: string) => Promise<GetNonUserAccess>;
234
220
  export {};
235
221
 
@@ -239,9 +225,24 @@ declare module '@amedia/user/clients/jupiter.spec' {
239
225
 
240
226
  }
241
227
  declare module '@amedia/user/clients/mercury' {
228
+ import { Array, Literal, Record, Static, String, Union } from 'runtypes';
242
229
  export class UserDeactivatedError extends Error {
243
230
  }
231
+ export enum AffiliationType {
232
+ ACCESS = "access",
233
+ FAMILY = "family",
234
+ SUBSCRIPTION = "subscription"
235
+ }
236
+ const PrimarySiteSchema: Record<{
237
+ domain: String;
238
+ name: String;
239
+ affiliation: Literal<AffiliationType.ACCESS>;
240
+ affiliations: Array<Union<[Literal<AffiliationType.ACCESS>, Literal<AffiliationType.FAMILY>, Literal<AffiliationType.SUBSCRIPTION>]>, false>;
241
+ }, false>;
242
+ export type PrimarySite = Static<typeof PrimarySiteSchema>;
244
243
  export const activateSubscription: (accessFeatures: string[], siteDomain: string) => Promise<string[]>;
244
+ export const getPrimarySite: (accessFeatures: string[]) => Promise<PrimarySite | null>;
245
+ export {};
245
246
 
246
247
  }
247
248
  declare module '@amedia/user/clients/mercury.spec' {
@@ -491,16 +492,11 @@ declare module '@amedia/user/janitor/jobs/removeUserStorage.spec' {
491
492
 
492
493
  }
493
494
  declare module '@amedia/user/lib/PaywallUnlockRequest' {
494
- export enum AffiliationType {
495
- ACCESS = "access"
496
- }
495
+ import { PrimarySite } from '@amedia/user/clients/mercury';
497
496
  export type UnlockResponse = {
498
497
  isLoggedIn: boolean;
499
498
  hasAccess: boolean;
500
- primarySite?: null | {
501
- domain: string;
502
- affiliation: AffiliationType;
503
- };
499
+ primarySite?: null | PrimarySite;
504
500
  accessFeatures: string[];
505
501
  };
506
502
  class PaywallUnlockRequest {
@@ -800,6 +796,6 @@ declare module '@amedia/user/utils/url.spec' {
800
796
 
801
797
  }
802
798
  declare module '@amedia/user' {
803
- import main = require('@amedia/user/src');
799
+ import main = require('@amedia/user/src/index');
804
800
  export = main;
805
801
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amedia/user",
3
- "version": "0.14.16",
3
+ "version": "0.14.18",
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)",
@@ -1,5 +1,4 @@
1
1
  import fetch from 'jest-fetch-mock';
2
- import { ValidationError } from 'runtypes';
3
2
  import cache from '../cache';
4
3
  import log from '../utils/log';
5
4
  import {
@@ -10,7 +9,6 @@ import {
10
9
  GetVstoken,
11
10
  GetNonUserAccess,
12
11
  getNonUserAccess,
13
- getSitesWithAccessFeatures,
14
12
  } from './jupiter';
15
13
  import anything = jasmine.anything;
16
14
  import spyOn = jest.spyOn;
@@ -177,74 +175,4 @@ describe('jupiter service', () => {
177
175
  );
178
176
  });
179
177
  });
180
-
181
- describe('GET /sites_with_access_features', () => {
182
- describe('with bad response', () => {
183
- beforeEach(() => {
184
- fetch.mockResponseOnce(JSON.stringify({ status: 'no_session_found' }), {
185
- status: 400,
186
- });
187
- });
188
-
189
- it('should throw error', async () => {
190
- await expect(
191
- getSitesWithAccessFeatures({ accessFeatures: ['newspaper'] })
192
- ).rejects.toThrow('Request not ok (400: Bad Request).');
193
- });
194
- });
195
-
196
- describe('with invalid schema', () => {
197
- beforeEach(() => {
198
- log.error = jest.fn();
199
- fetch.mockResponseOnce(JSON.stringify([{ invalid: 'schema' }]));
200
- });
201
-
202
- it('should throw error', async () => {
203
- await expect(
204
- getSitesWithAccessFeatures({
205
- accessFeatures: ['newspaper'],
206
- excludeBundles: true,
207
- })
208
- ).rejects.toThrow(
209
- 'Expected { key: string; domain: string; name: { full: string; short: string; }; }[], but was incompatible'
210
- );
211
- expect(log.error).toHaveBeenCalledWith(jasmine.any(ValidationError), {
212
- json: [{ invalid: 'schema' }],
213
- });
214
- });
215
- });
216
-
217
- describe('with valid data', () => {
218
- beforeEach(() => {
219
- log.error = jest.fn();
220
- fetch.mockResponseOnce(
221
- JSON.stringify([
222
- {
223
- key: 'telen__',
224
- name: {
225
- full: 'Telen',
226
- short: 'Telen',
227
- },
228
- domain: 'www.telen.no',
229
- },
230
- ])
231
- );
232
- });
233
-
234
- it('should return expected', async () => {
235
- await expect(
236
- getSitesWithAccessFeatures({ accessFeatures: ['newspaper'] })
237
- ).resolves.toEqual([
238
- {
239
- key: 'telen__',
240
- name: {
241
- full: 'Telen',
242
- short: 'Telen',
243
- },
244
- domain: 'www.telen.no',
245
- },
246
- ]);
247
- });
248
- });
249
- });
250
178
  });
@@ -34,19 +34,6 @@ 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
-
50
37
  const GetNonUserAccessSchema = Record({
51
38
  status: Literal('success'),
52
39
  vstoken_cookie: String,
@@ -108,42 +95,6 @@ export const getUserAccess = (siteDomain: string): Promise<GetVstoken> =>
108
95
  }
109
96
  });
110
97
 
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
-
147
98
  export const getNonUserAccess = (
148
99
  siteDomain: string
149
100
  ): Promise<GetNonUserAccess> =>
@@ -1,5 +1,12 @@
1
1
  import fetch from 'jest-fetch-mock';
2
- import { activateSubscription, UserDeactivatedError } from './mercury';
2
+ import { ValidationError } from 'runtypes';
3
+ import {
4
+ activateSubscription,
5
+ AffiliationType,
6
+ getPrimarySite,
7
+ UserDeactivatedError,
8
+ } from './mercury';
9
+ import log from '../utils/log';
3
10
 
4
11
  describe('activateSubscription()', () => {
5
12
  it('should throw error if user is deactivated', async () => {
@@ -62,3 +69,58 @@ describe('activateSubscription()', () => {
62
69
  ).resolves.toEqual(['newspaper']);
63
70
  });
64
71
  });
72
+
73
+ describe('GET /primary_site', () => {
74
+ describe('with bad response', () => {
75
+ beforeEach(() => {
76
+ fetch.mockResponseOnce(JSON.stringify({ status: 'no_session_found' }), {
77
+ status: 400,
78
+ });
79
+ });
80
+
81
+ it('should return null', async () => {
82
+ await expect(getPrimarySite(['newspaper'])).resolves.toEqual(null);
83
+ });
84
+ });
85
+
86
+ describe('with invalid schema', () => {
87
+ beforeEach(() => {
88
+ log.error = jest.fn();
89
+ fetch.mockResponseOnce(JSON.stringify([{ invalid: 'schema' }]));
90
+ });
91
+
92
+ it('should return null', async () => {
93
+ await expect(getPrimarySite(['newspaper'])).resolves.toBeNull();
94
+ expect(log.error).toHaveBeenCalledWith(jasmine.any(ValidationError), {
95
+ json: [{ invalid: 'schema' }],
96
+ });
97
+ });
98
+ });
99
+
100
+ describe('with valid data', () => {
101
+ beforeEach(() => {
102
+ log.error = jest.fn();
103
+ fetch.mockResponseOnce(
104
+ JSON.stringify({
105
+ name: 'Telen',
106
+ domain: 'www.telen.no',
107
+ affiliation: 'access',
108
+ affiliations: ['access', 'family', 'subscription'],
109
+ })
110
+ );
111
+ });
112
+
113
+ it('should return expected', async () => {
114
+ await expect(getPrimarySite(['newspaper'])).resolves.toEqual({
115
+ name: 'Telen',
116
+ domain: 'www.telen.no',
117
+ affiliation: AffiliationType.ACCESS,
118
+ affiliations: [
119
+ AffiliationType.ACCESS,
120
+ AffiliationType.FAMILY,
121
+ AffiliationType.SUBSCRIPTION,
122
+ ],
123
+ });
124
+ });
125
+ });
126
+ });
@@ -1,3 +1,4 @@
1
+ import { Array, Literal, Record, Static, String, Union } from 'runtypes';
1
2
  import log from '../utils/log';
2
3
 
3
4
  export class UserDeactivatedError extends Error {}
@@ -8,6 +9,27 @@ const EXPECTED_ERRORS = [
8
9
  'publication_not_subscribable', // Activation is not possible on current publication
9
10
  ];
10
11
 
12
+ export enum AffiliationType {
13
+ ACCESS = 'access',
14
+ FAMILY = 'family',
15
+ SUBSCRIPTION = 'subscription',
16
+ }
17
+
18
+ const PrimarySiteSchema = Record({
19
+ domain: String,
20
+ name: String,
21
+ affiliation: Literal(AffiliationType.ACCESS),
22
+ affiliations: Array(
23
+ Union(
24
+ Literal(AffiliationType.ACCESS),
25
+ Literal(AffiliationType.FAMILY),
26
+ Literal(AffiliationType.SUBSCRIPTION)
27
+ )
28
+ ),
29
+ });
30
+
31
+ export type PrimarySite = Static<typeof PrimarySiteSchema>;
32
+
11
33
  export const activateSubscription = async (
12
34
  accessFeatures: string[],
13
35
  siteDomain: string
@@ -46,3 +68,38 @@ export const activateSubscription = async (
46
68
  }
47
69
  return data?.access_features;
48
70
  });
71
+
72
+ export const getPrimarySite = (
73
+ accessFeatures: string[]
74
+ ): Promise<PrimarySite | null> =>
75
+ fetch(
76
+ `/api/mercury/v2/access/primary_site?${new URLSearchParams({
77
+ access_features: accessFeatures.join(','),
78
+ })}`,
79
+ {
80
+ method: 'get',
81
+ }
82
+ )
83
+ .then((response) => {
84
+ if (!response.ok) {
85
+ log.error(
86
+ `Failed to get primary site for user: Request not ok (${response.status}: ${response.statusText}).`
87
+ );
88
+ return null;
89
+ }
90
+ if (response.status === 204) {
91
+ return null; // No primary site found
92
+ }
93
+ return response.json();
94
+ })
95
+ .then((json) => {
96
+ if (json === null) {
97
+ return null;
98
+ }
99
+ try {
100
+ return PrimarySiteSchema.check(json);
101
+ } catch (error) {
102
+ log.error(error, { json });
103
+ return null;
104
+ }
105
+ });
@@ -1,12 +1,10 @@
1
- import PaywallUnlockRequest, {
2
- AffiliationType,
3
- UnlockResponse,
4
- } from './PaywallUnlockRequest';
1
+ import PaywallUnlockRequest, { UnlockResponse } from './PaywallUnlockRequest';
5
2
  import * as authorization from '../actions/authorization';
6
3
  import * as location from '../utils/location';
7
4
  import * as autologin from '../autologin';
8
5
  import * as localhostCheck from '../utils/localhostCheck';
9
- import * as jupiter from '../clients/jupiter';
6
+ import * as mercury from '../clients/mercury';
7
+ import { AffiliationType } from '../clients/mercury';
10
8
  import store from '../store';
11
9
  import PaywallError from '../exceptions/PaywallError';
12
10
  import { listenForUserAttributeRequests } from '../eventHandlers/userAttributes';
@@ -57,11 +55,7 @@ function itShouldHaveAskedForSitesThatProvideRequestedAccessFeatures(
57
55
  accessFeatures: string[]
58
56
  ) {
59
57
  it('should have asked for sites', () => {
60
- expect(jupiter.getSitesWithAccessFeatures).toHaveBeenCalledWith({
61
- accessFeatures,
62
- excludeBundles: true,
63
- sortBy: 'veiklasse',
64
- });
58
+ expect(mercury.getPrimarySite).toHaveBeenCalledWith(accessFeatures);
65
59
  });
66
60
  }
67
61
 
@@ -314,13 +308,15 @@ describe('PaywallUnlocker', () => {
314
308
  accessFeatures: [],
315
309
  });
316
310
  spyOn(authorization, 'activate').mockResolvedValue([]);
317
- spyOn(jupiter, 'getSitesWithAccessFeatures').mockResolvedValue([
318
- {
319
- key: 'telen__',
320
- domain: 'www.telen.no',
321
- name: { full: 'Telen', short: 'Telen' },
322
- },
323
- ]);
311
+ spyOn(mercury, 'getPrimarySite').mockResolvedValue({
312
+ domain: 'www.telen.no',
313
+ name: 'Telen',
314
+ affiliation: AffiliationType.ACCESS,
315
+ affiliations: [
316
+ AffiliationType.ACCESS,
317
+ AffiliationType.SUBSCRIPTION,
318
+ ],
319
+ });
324
320
  unlockResponse = await new PaywallUnlockRequest().tryUnlock();
325
321
  });
326
322
 
@@ -333,6 +329,10 @@ describe('PaywallUnlocker', () => {
333
329
  name: 'Telen',
334
330
  domain: 'www.telen.no',
335
331
  affiliation: AffiliationType.ACCESS,
332
+ affiliations: [
333
+ AffiliationType.ACCESS,
334
+ AffiliationType.SUBSCRIPTION,
335
+ ],
336
336
  },
337
337
  });
338
338
  });
@@ -353,7 +353,7 @@ describe('PaywallUnlocker', () => {
353
353
  accessFeatures: ['newspaper'],
354
354
  });
355
355
  spyOn(authorization, 'activate').mockResolvedValue(['newspaper']);
356
- spyOn(jupiter, 'getSitesWithAccessFeatures').mockResolvedValue([]);
356
+ spyOn(mercury, 'getPrimarySite').mockResolvedValue(null);
357
357
  unlockResponse = await new PaywallUnlockRequest()
358
358
  .withAccessFeatures(['plussalt'])
359
359
  .tryUnlock();
@@ -9,40 +9,19 @@ import { getCurrentSiteDomain } from '../utils/url';
9
9
  import PaywallError from '../exceptions/PaywallError';
10
10
  import UserDataRequest from './UserDataRequest';
11
11
  import { attemptPaywallAutoLogin } from '../autologin';
12
- import { AccessFeatures, getSitesWithAccessFeatures } from '../clients/jupiter';
12
+ import { AccessFeatures } from '../clients/jupiter';
13
13
  import { isRunningOnLocalhost } from '../utils/localhostCheck';
14
14
  import { reload, replace } from '../utils/location';
15
15
 
16
- export enum AffiliationType {
17
- ACCESS = 'access',
18
- }
16
+ import { getPrimarySite, PrimarySite } from '../clients/mercury';
19
17
 
20
18
  export type UnlockResponse = {
21
19
  isLoggedIn: boolean;
22
20
  hasAccess: boolean;
23
- primarySite?: null | { domain: string; affiliation: AffiliationType };
21
+ primarySite?: null | PrimarySite;
24
22
  accessFeatures: string[];
25
23
  };
26
24
 
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 access 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
-
46
25
  class PaywallUnlockRequest {
47
26
  private requestedAccessFeatures: string[] = ['newspaper'];
48
27