@amedia/user 0.6.1 → 0.7.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.
@@ -1,3 +1,18 @@
1
+ /*!
2
+ localForage -- Offline Storage, Improved
3
+ Version 1.9.0
4
+ https://localforage.github.io/localForage
5
+ (c) 2013-2017 Mozilla, Apache License 2.0
6
+ */
7
+
8
+ /*!
9
+ * JavaScript Cookie v2.2.1
10
+ * https://github.com/js-cookie/js-cookie
11
+ *
12
+ * Copyright 2006, 2015 Klaus Hartl & Fagner Brack
13
+ * Released under the MIT license
14
+ */
15
+
1
16
  /**
2
17
  * @license
3
18
  * Lodash <https://lodash.com/>
@@ -0,0 +1,13 @@
1
+ import { State, UserAttributes } from '../types';
2
+ declare type StoreDataMap = {
3
+ userAttributes: UserAttributes;
4
+ state: State;
5
+ };
6
+ declare type Listener<T> = (data: T) => void;
7
+ declare const _default: {
8
+ set: (key: keyof StoreDataMap, value: UserAttributes | State) => void;
9
+ get: <K extends keyof StoreDataMap, T = StoreDataMap[K]>(key: K) => T | undefined;
10
+ on: <K_1 extends keyof StoreDataMap, T_1 = StoreDataMap[K_1]>(key: K_1, listener: Listener<T_1>) => void;
11
+ clear: () => void;
12
+ };
13
+ export default _default;
@@ -0,0 +1 @@
1
+ export {};
package/dist/types.d.ts CHANGED
@@ -3,7 +3,9 @@ export declare type UserAttributes = {
3
3
  email?: string;
4
4
  phone?: string;
5
5
  trackingKey?: string;
6
- extraData?: [];
6
+ extraData?: {
7
+ [index: string]: unknown;
8
+ };
7
9
  access?: string[];
8
10
  privacyPreferences?: PrivacyPreferences;
9
11
  };
@@ -1,3 +1,6 @@
1
1
  import { Runtype, Static } from 'runtypes';
2
- declare const getOrUpdate: <T extends Runtype<unknown>>(key: string, schema: T, action: () => Promise<Static<T>>) => Promise<Static<T>>;
3
- export default getOrUpdate;
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>): Promise<Static<T>>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amedia/user",
3
- "version": "0.6.1",
3
+ "version": "0.7.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)",
@@ -11,6 +11,7 @@
11
11
  "build": "webpack --mode=production"
12
12
  },
13
13
  "dependencies": {
14
+ "@amedia/browserid": "0.1.6",
14
15
  "@amedia/frontend-rpc": "0.0.12",
15
16
  "dexie": "3.0.3",
16
17
  "lodash": "4.17.21",
@@ -1,16 +1,10 @@
1
- import {
2
- getCurrentSession,
3
- InternalSessionSchema,
4
- removeSession,
5
- Session,
6
- } from '../clients/pluto';
1
+ import { getCurrentSession, removeSession } from '../clients/pluto';
7
2
  import cache from '../cache';
8
3
  import { getRPCClient } from '../lib/rpc';
9
4
  import { removeCookie } from '../lib/cookie';
10
5
  import { getCurrentEnvironment } from '../utils/url';
11
6
  import log from '../utils/log';
12
-
13
- const EXPIRES_10_SECONDS = 10000;
7
+ import { UserAttributes } from '../types';
14
8
 
15
9
  export const login = (requestedUrl: string) => {
16
10
  const environment = getCurrentEnvironment();
@@ -34,41 +28,14 @@ export const logout = async () =>
34
28
  // TODO: It now clears the entire cache. Might be too aggressive.
35
29
  Promise.all([removeSession(window.location.host), cache.clear()])
36
30
  .then(() => {
31
+ // TODO This should be separated from logout and instead be setup to listen on state changes on storage
37
32
  getRPCClient().userAuthenticated(false);
38
33
  clearCookies();
39
34
  // In addition to removing the regular cookies we also want to remove VSTOKEN2 on explicit logout
40
35
  removeCookie('VSTOKEN2');
41
- /* @todo Set state
42
- * state.set('state', {
43
- isLoggedIn: false,
44
- }); */
45
36
  })
46
37
  .catch((reason) => {
47
- log.error('Failiure while logging out', reason);
38
+ log.error('Failure while logging out', reason);
48
39
  });
49
40
 
50
- let isFetchingSession = false;
51
- const IS_LOGGED_IN_CACHE_KEY = 'is_logged_in';
52
- export const getSession = async (): Promise<Session | null> => {
53
- if (isFetchingSession) {
54
- // TODO Perhaps return a promise to be resolved later?
55
- return null;
56
- }
57
- isFetchingSession = true;
58
-
59
- // Try the cache first
60
- const cacheResponse = await cache.get(
61
- IS_LOGGED_IN_CACHE_KEY,
62
- InternalSessionSchema
63
- );
64
- if (cacheResponse) {
65
- isFetchingSession = false;
66
- return cacheResponse;
67
- }
68
-
69
- // Actually perform a request against backend for the session
70
- const session = await getCurrentSession();
71
- cache.set(IS_LOGGED_IN_CACHE_KEY, session, EXPIRES_10_SECONDS);
72
- isFetchingSession = false;
73
- return session;
74
- };
41
+ export const getSession = (): Promise<UserAttributes> => getCurrentSession();
@@ -1,32 +1,32 @@
1
+ import { getBrowserId } from '@amedia/browserid';
1
2
  import log from '../utils/log';
2
3
  import { UserAttributes } from '../types';
3
4
  import { getSession } from './authentication';
4
5
  import { getAccess } from './authorization';
5
6
  import { getPrivacyPreferences } from './preferences';
7
+ import store from '../store';
8
+ import { getInfo } from '../clients/nebula';
9
+
10
+ const getExtraData = () =>
11
+ getBrowserId().then((browserId) =>
12
+ getInfo(
13
+ window.location.hostname,
14
+ browserId,
15
+ store.get('userAttributes')?.trackingKey
16
+ )
17
+ );
6
18
 
7
- // TODO We may want actions to tell us what they can deliver and not have this "organizer" (wohoo-bad-name) tell the actions..
8
19
  const dataServiceMap: {
9
- // TODO Must get proper type here. Perhaps all actions should return UserAttribute-compatible response?
10
- [key in keyof UserAttributes]?: () => Promise<UserAttributes>;
20
+ [key in keyof UserAttributes]?: () => Promise<Partial<UserAttributes>>;
11
21
  } = {
12
- // @ts-ignore
13
22
  name: getSession,
14
- // @ts-ignore
15
23
  trackingKey: getSession,
16
24
  access: getAccess,
25
+ extraData: getExtraData,
17
26
  privacyPreferences: getPrivacyPreferences,
18
27
  };
19
28
 
20
- let currentUserData: UserAttributes = {};
21
- const addToCurrentUserData = (data) => {
22
- currentUserData = { ...currentUserData, ...data };
23
- };
24
- const getCurrentUserData = () => currentUserData;
25
-
26
- export const fetchDataBasedOnAttributes = (
27
- attributes: Array<keyof UserAttributes>,
28
- onDataUpdated: (attributes: UserAttributes) => void
29
- ) => {
29
+ export const requestAttributes = (attributes: Array<keyof UserAttributes>) => {
30
30
  const requiredServices: Array<() => Promise<UserAttributes>> = [];
31
31
  attributes.forEach((attribute) => {
32
32
  const service = dataServiceMap[attribute];
@@ -43,10 +43,8 @@ export const fetchDataBasedOnAttributes = (
43
43
  const service = requiredServices.pop();
44
44
  if (service) {
45
45
  service()
46
- .then((a) => {
47
- addToCurrentUserData(a);
48
- onDataUpdated(getCurrentUserData());
49
- })
46
+ // TODO we need to discuss where to do the store updates. userAttributes vs state.
47
+ .then((data) => store.set('userAttributes', data))
50
48
  .catch((error) => {
51
49
  log.error('Call rejected', service, error);
52
50
  });
@@ -1,4 +1,5 @@
1
1
  import fetch from 'jest-fetch-mock';
2
+ import cache from '../cache';
2
3
  import log from '../utils/log';
3
4
  import {
4
5
  checkForAccess,
@@ -10,8 +11,9 @@ import {
10
11
  getNonUserAccess,
11
12
  } from './jupiter';
12
13
 
13
- beforeEach(() => {
14
+ beforeEach(async () => {
14
15
  fetch.resetMocks();
16
+ await cache.clear();
15
17
  });
16
18
 
17
19
  describe('jupiter service', () => {
@@ -50,7 +52,7 @@ describe('jupiter service', () => {
50
52
 
51
53
  await expect(
52
54
  checkForAccess(publicationDomain, accessFeatures)
53
- ).rejects.toThrow('Request not ok (400: Bad Request).');
55
+ ).rejects.toBeUndefined();
54
56
  });
55
57
 
56
58
  it('should fail on runtime validation', async () => {
@@ -59,9 +61,7 @@ describe('jupiter service', () => {
59
61
 
60
62
  await expect(
61
63
  checkForAccess(publicationDomain, accessFeatures)
62
- ).rejects.toThrow(
63
- 'Expected { status: "success"; access: "granted" | "denied"; publication: { id: number; domain: string; }; access_features: string[]; }, but was incompatible'
64
- );
64
+ ).rejects.toBeUndefined();
65
65
  });
66
66
  });
67
67
 
@@ -8,6 +8,7 @@ import {
8
8
  Union,
9
9
  } from 'runtypes';
10
10
  import log from '../utils/log';
11
+ import getOrUpdate from '../utils/getOrUpdate';
11
12
 
12
13
  export type AccessFeatures = string[];
13
14
 
@@ -45,28 +46,33 @@ export const checkForAccess = (
45
46
  publicationDomain: string,
46
47
  accessFeatures: AccessFeatures
47
48
  ): Promise<CheckAccessForPaper> =>
48
- fetch(
49
- `/api/jupiter/v1/check_access_for_paper/${publicationDomain}/?require=any&access_features=${accessFeatures.join(
50
- ','
51
- )}`
52
- )
53
- .then((response) => {
54
- if (!response.ok) {
55
- // TODO Handle this.
56
- throw new Error(
57
- `Request not ok (${response.status}: ${response.statusText}).`
58
- );
59
- }
60
- return response.json();
61
- })
62
- .then((json) => {
63
- try {
64
- return CheckAccessForPaperSchema.check(json);
65
- } catch (error) {
66
- log.error('Invalid schema', error);
67
- throw error;
68
- }
69
- });
49
+ getOrUpdate('checkForAccess', CheckAccessForPaperSchema, () =>
50
+ fetch(
51
+ `/api/jupiter/v1/check_access_for_paper/${publicationDomain}/?require=any&access_features=${accessFeatures.join(
52
+ ','
53
+ )}`
54
+ )
55
+ .then((response) => {
56
+ if (!response.ok) {
57
+ // TODO Handle this.
58
+ throw new Error(
59
+ `Request not ok (${response.status}: ${response.statusText}).`
60
+ );
61
+ }
62
+ return response.json();
63
+ })
64
+ .then((json) => {
65
+ try {
66
+ return {
67
+ ttl: 1000 * 10, // 10 seconds
68
+ data: CheckAccessForPaperSchema.check(json),
69
+ };
70
+ } catch (error) {
71
+ log.error('Invalid schema', error);
72
+ throw error;
73
+ }
74
+ })
75
+ );
70
76
 
71
77
  export const getVstoken = (publicationDomain: string): Promise<GetVstoken> =>
72
78
  fetch(`/api/jupiter/v1/get_vstoken/${publicationDomain}`, { method: 'post' })
@@ -1,10 +1,12 @@
1
1
  import fetch from 'jest-fetch-mock';
2
+ import cache from '../cache';
2
3
  import log from '../utils/log';
3
- import { Info, getInfo } from './nebula';
4
+ import { getInfo } from './nebula';
4
5
 
5
6
  describe('nebula service', () => {
6
- beforeEach(() => {
7
+ beforeEach(async () => {
7
8
  fetch.resetMocks();
9
+ await cache.clear();
8
10
  });
9
11
 
10
12
  describe('GET /info', () => {
@@ -13,7 +15,7 @@ describe('nebula service', () => {
13
15
  const browserId = 'fc0bce06-560b-48e4-92f2-840e67178516';
14
16
 
15
17
  it('should return user information', async () => {
16
- const response: Info = {
18
+ const response = {
17
19
  ad_segments: '1022776316,1037513379,1043845105',
18
20
  ad_segments_user: '1022776316,1037513379,1043845105',
19
21
  age: 28,
@@ -35,11 +37,11 @@ describe('nebula service', () => {
35
37
  fetch.mockResponseOnce(JSON.stringify(response));
36
38
 
37
39
  await expect(
38
- getInfo(userKey, publicationDomain, browserId)
39
- ).resolves.toEqual(response);
40
+ getInfo(publicationDomain, browserId, userKey)
41
+ ).resolves.toEqual({ extraData: response });
40
42
 
41
43
  expect(fetch).toHaveBeenCalledWith(
42
- `https://services.gcloud.api.no/api/nebula/v1/info?user_key=${userKey}&domain=${publicationDomain}&browser_id=${browserId}`
44
+ `https://services.gcloud.api.no/api/nebula/v1/info?domain=${publicationDomain}&browser_id=${browserId}&user_key=${userKey}`
43
45
  );
44
46
  });
45
47
 
@@ -49,13 +51,11 @@ describe('nebula service', () => {
49
51
 
50
52
  await expect(
51
53
  getInfo(userKey, publicationDomain, browserId)
52
- ).rejects.toThrow(
53
- 'Expected { ad_segments?: string; ad_segments_user?: string; age?: number; age_user?: number; birth_year?: string; birth_year_user?: string; gender?: string; gender_user?: string; grunnkrets?: string; grunnkrets_user?: string; postcode?: string; postcode_user?: string; shared_account?: boolean; shared_account_user?: boolean; user_grouping_number?: string; user_grouping_number_user?: string; }, but was incompatible'
54
- );
54
+ ).rejects.toBeUndefined();
55
55
  });
56
56
 
57
57
  it('should pass on runtime validation if unknown property is given', async () => {
58
- const response: Info = {
58
+ const response = {
59
59
  fullname: 'ra. dean baskaran',
60
60
  age: 28,
61
61
  shared_account: false,
@@ -65,7 +65,7 @@ describe('nebula service', () => {
65
65
 
66
66
  await expect(
67
67
  getInfo(userKey, publicationDomain, browserId)
68
- ).resolves.toEqual(response);
68
+ ).resolves.toEqual({ extraData: response });
69
69
  });
70
70
  });
71
71
  });
@@ -8,6 +8,8 @@ import {
8
8
  Boolean,
9
9
  } from 'runtypes';
10
10
  import log from '../utils/log';
11
+ import getOrUpdate from '../utils/getOrUpdate';
12
+ import { UserAttributes } from '../types';
11
13
 
12
14
  const InfoSchema = Dictionary(Unknown, String).And(
13
15
  Partial({
@@ -30,22 +32,43 @@ const InfoSchema = Dictionary(Unknown, String).And(
30
32
  })
31
33
  );
32
34
 
33
- export type Info = Static<typeof InfoSchema>;
34
-
35
- export const getInfo = (
36
- userKey: string,
35
+ const getNebulaData = (
37
36
  publicationDomain: string,
38
- browserId: string
39
- ): Promise<Info> =>
40
- fetch(
41
- `https://services.gcloud.api.no/api/nebula/v1/info?user_key=${userKey}&domain=${publicationDomain}&browser_id=${browserId}`
42
- )
37
+ browserId: string,
38
+ trackingKey?: string
39
+ ) => {
40
+ const url = new URL('https://services.gcloud.api.no/api/nebula/v1/info');
41
+ url.searchParams.set('domain', publicationDomain);
42
+ url.searchParams.set('browser_id', browserId);
43
+ if (trackingKey) {
44
+ url.searchParams.set('user_key', trackingKey);
45
+ }
46
+ return fetch(url.toString())
43
47
  .then((response) => response.json())
44
48
  .then((json) => {
45
49
  try {
46
- return InfoSchema.check(json);
50
+ return {
51
+ ttl: 1000 * 60 * 60 * 5, // Cache 5 mins
52
+ data: InfoSchema.check(json),
53
+ };
47
54
  } catch (error) {
48
55
  log.error('Invalid schema', error);
49
56
  throw error;
50
57
  }
51
58
  });
59
+ };
60
+
61
+ const mapNebulaToUserData = (
62
+ data: Static<typeof InfoSchema>
63
+ ): Pick<UserAttributes, 'extraData'> => ({
64
+ extraData: data,
65
+ });
66
+
67
+ export const getInfo = (
68
+ publicationDomain: string,
69
+ browserId: string,
70
+ userKey?: string
71
+ ): Promise<Pick<UserAttributes, 'extraData'>> =>
72
+ getOrUpdate('getNebulaInfo', InfoSchema, () =>
73
+ getNebulaData(publicationDomain, browserId, userKey)
74
+ ).then(mapNebulaToUserData);
@@ -1,14 +1,16 @@
1
1
  import fetch from 'jest-fetch-mock';
2
+ import cache from '../cache';
2
3
  import { getCurrentSession, removeSession } from './pluto';
3
4
 
4
5
  fetch.enableMocks();
5
6
 
6
- beforeEach(() => {
7
+ beforeEach(async () => {
7
8
  fetch.resetMocks();
9
+ await cache.clear();
8
10
  });
9
11
 
10
12
  describe('Pluto service', () => {
11
- it('getCurrentSession() should return session data', () => {
13
+ it('getCurrentSession() should return session data', async () => {
12
14
  const data = {
13
15
  created_at:
14
16
  'Wed Apr 28 2021 16:02:04 GMT+0200 (Central European Summer Time)',
@@ -20,7 +22,8 @@ describe('Pluto service', () => {
20
22
  };
21
23
  fetch.mockResponseOnce(JSON.stringify(data));
22
24
 
23
- expect(getCurrentSession()).resolves.toEqual({
25
+ const currentSession = await getCurrentSession();
26
+ expect(currentSession).toEqual({
24
27
  name: 'Earl Hickey',
25
28
  trackingKey: 'some tracking key',
26
29
  });
@@ -1,47 +1,57 @@
1
1
  import { Record, Static, String } from 'runtypes';
2
2
  import log from '../utils/log';
3
+ import getOrUpdate from '../utils/getOrUpdate';
4
+ import store from '../store';
5
+ import { UserAttributes } from '../types';
3
6
 
4
7
  const ServiceSessionSchema = Record({
5
8
  user_name: String,
6
9
  tracking_key: String,
7
10
  });
8
11
 
9
- export const InternalSessionSchema = Record({
10
- name: String,
11
- trackingKey: String,
12
- });
13
-
14
- // eslint-disable-next-line @typescript-eslint/no-redeclare
15
- export type Session = Static<typeof InternalSessionSchema>;
16
-
17
- const mapSession = (session: Static<typeof ServiceSessionSchema>): Session => ({
12
+ const mapSessionToUserAttributes = (
13
+ session: Static<typeof ServiceSessionSchema>
14
+ ): UserAttributes => ({
18
15
  name: session.user_name,
19
16
  trackingKey: session.tracking_key,
20
17
  });
21
18
 
22
- export const getCurrentSession = async (): Promise<Session> =>
19
+ const fetchCurrentSession = () =>
23
20
  fetch(`/api/pluto/v1/sessions/current`)
24
21
  .then((response) => {
25
22
  if (!response.ok) {
26
23
  if (response.status === 403) {
27
- return Promise.reject();
24
+ store.set('state', { isLoggedIn: false });
25
+ return {};
28
26
  }
29
- // TODO Handle this.
30
- throw new Error(
31
- `Request not ok (${response.status}: ${response.statusText}).`
27
+ log.error(
28
+ `Unknown error (${response.status}: ${response.statusText}) when fetching current session`,
29
+ { response }
32
30
  );
31
+ return Promise.reject();
33
32
  }
33
+ store.set('state', { isLoggedIn: true });
34
34
  return response.json();
35
35
  })
36
36
  .then((json) => {
37
37
  try {
38
- return mapSession(ServiceSessionSchema.check(json));
38
+ return {
39
+ ttl: 10000,
40
+ data: ServiceSessionSchema.check(json),
41
+ };
39
42
  } catch (error) {
40
43
  log.error('Invalid schema', error);
41
44
  throw error;
42
45
  }
43
46
  });
44
47
 
48
+ export const getCurrentSession = async (): Promise<UserAttributes> =>
49
+ getOrUpdate(
50
+ 'getCurrentSession',
51
+ ServiceSessionSchema,
52
+ fetchCurrentSession
53
+ ).then(mapSessionToUserAttributes);
54
+
45
55
  export const removeSession = async (domain: string) =>
46
56
  fetch(`/api/pluto/v1/sessions/current?publication_domain=${domain}`, {
47
57
  method: 'DELETE',
@@ -55,5 +65,5 @@ export const removeSession = async (domain: string) =>
55
65
  `Error, could not perform deleteRequest. Status: ${res.status} Text: ${res.statusText}`
56
66
  );
57
67
  }
58
- // TODO Update state isLoggedIn
68
+ store.set('state', { isLoggedIn: false });
59
69
  });
@@ -1,6 +1,7 @@
1
- import { fetchDataBasedOnAttributes } from '../actions/userData';
1
+ import { requestAttributes } from '../actions/userData';
2
2
  import { dispatch, listenWithExclusivity } from '../utils/customEventWrapper';
3
3
  import { State, UserAttributes } from '../types';
4
+ import store from '../store';
4
5
 
5
6
  export enum AmediaUserEvents {
6
7
  REQUEST_USER_ATTRIBUTES = 'amedia-user.request-user-attributes',
@@ -19,14 +20,20 @@ declare global {
19
20
  }
20
21
 
21
22
  export const listenForUserAttributeRequests = () => {
23
+ store.on('userAttributes', (user) => {
24
+ dispatch(
25
+ new CustomEvent(AmediaUserEvents.ON_ATTRIBUTES_UPDATED, {
26
+ detail: user,
27
+ })
28
+ );
29
+ });
30
+ store.on('state', (state) => {
31
+ dispatch(
32
+ new CustomEvent(AmediaUserEvents.ON_STATE_UPDATED, { detail: state })
33
+ );
34
+ });
22
35
  listenWithExclusivity(AmediaUserEvents.REQUEST_USER_ATTRIBUTES, (evt) => {
23
- fetchDataBasedOnAttributes(evt.detail, (attributes) => {
24
- dispatch(
25
- new CustomEvent(AmediaUserEvents.ON_ATTRIBUTES_UPDATED, {
26
- detail: attributes,
27
- })
28
- );
29
- });
36
+ requestAttributes(evt.detail);
30
37
  });
31
38
  };
32
39