@amedia/user 0.1.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.
Files changed (60) hide show
  1. package/.eslintrc +6 -0
  2. package/.prettierrc.json +1 -0
  3. package/README.md +60 -0
  4. package/dist/index.d.ts +20 -0
  5. package/dist/index.js +44 -0
  6. package/dist/lib/authentication.d.ts +20 -0
  7. package/dist/lib/authentication.js +78 -0
  8. package/dist/lib/authorization.d.ts +15 -0
  9. package/dist/lib/authorization.js +55 -0
  10. package/dist/lib/cache/db.d.ts +6 -0
  11. package/dist/lib/cache/db.js +13 -0
  12. package/dist/lib/cache/global.d.ts +9 -0
  13. package/dist/lib/cache/global.js +16 -0
  14. package/dist/lib/cache/types.d.ts +5 -0
  15. package/dist/lib/cache/types.js +2 -0
  16. package/dist/lib/dataOrganizer.d.ts +9 -0
  17. package/dist/lib/dataOrganizer.js +14 -0
  18. package/dist/lib/eventHandler.d.ts +3 -0
  19. package/dist/lib/eventHandler.js +11 -0
  20. package/dist/lib/queue.d.ts +5 -0
  21. package/dist/lib/queue.js +17 -0
  22. package/dist/lib/tools.d.ts +1 -0
  23. package/dist/lib/tools.js +2 -0
  24. package/dist/lib/types.d.ts +7 -0
  25. package/dist/lib/types.js +2 -0
  26. package/dist/lib/user.d.ts +2 -0
  27. package/dist/lib/user.js +5 -0
  28. package/dist/lib/userAttributes.d.ts +12 -0
  29. package/dist/lib/userAttributes.js +18 -0
  30. package/dist/services/cache.d.ts +9 -0
  31. package/dist/services/cache.js +34 -0
  32. package/dist/services/jupiter.d.ts +29 -0
  33. package/dist/services/jupiter.js +74 -0
  34. package/dist/services/mercury.d.ts +15 -0
  35. package/dist/services/mercury.js +32 -0
  36. package/dist/services/pluto.d.ts +12 -0
  37. package/dist/services/pluto.js +40 -0
  38. package/jest.config.js +7 -0
  39. package/package.json +34 -0
  40. package/setupJest.js +1 -0
  41. package/src/index.spec.ts +166 -0
  42. package/src/index.ts +58 -0
  43. package/src/lib/authentication.ts +94 -0
  44. package/src/lib/authorization.ts +86 -0
  45. package/src/lib/cache/db.ts +21 -0
  46. package/src/lib/cache/global.ts +23 -0
  47. package/src/lib/cache/types.ts +5 -0
  48. package/src/lib/dataOrganizer.ts +18 -0
  49. package/src/lib/eventHandler.ts +16 -0
  50. package/src/lib/queue.ts +19 -0
  51. package/src/lib/types.ts +7 -0
  52. package/src/lib/userAttributes.ts +32 -0
  53. package/src/services/cache.ts +36 -0
  54. package/src/services/jupiter.spec.ts +148 -0
  55. package/src/services/jupiter.ts +110 -0
  56. package/src/services/mercury.spec.ts +27 -0
  57. package/src/services/mercury.ts +47 -0
  58. package/src/services/pluto.ts +34 -0
  59. package/tsconfig.eslint.json +24 -0
  60. package/tsconfig.json +25 -0
@@ -0,0 +1,5 @@
1
+ export type Engine = {
2
+ get: (key: string) => Promise<unknown>;
3
+ set: (key: string, data: unknown, expires: number) => Promise<void>;
4
+ remove: (key: string) => Promise<void>;
5
+ };
@@ -0,0 +1,18 @@
1
+ import { UserAttributes } from './types';
2
+
3
+ /**
4
+ * Jeg tror ikke vi burde gjøre det slik som dette.
5
+ * Denne funksjonen var hentet ut fra userAttribute kun for å
6
+ * kunne mocke implementasjonen så jeg kunne teste event-callback mekanismen.
7
+ *
8
+ * En implementasjon som dette vil gjøre det vanskelig svare etterhvert som vi får data.
9
+ */
10
+
11
+ export const fetchDataBasedOnAttributes = (
12
+ attributes: (keyof UserAttributes)[]
13
+ ): UserAttributes =>
14
+ // TODO: Implement fetching based on attributes
15
+ ({
16
+ isLoggedIn: true,
17
+ name: 'Donald Duck',
18
+ });
@@ -0,0 +1,16 @@
1
+ let rootElement = window || global;
2
+
3
+ export const setRootElement = (element) => {
4
+ rootElement = element;
5
+ };
6
+
7
+ export const listen = <T extends keyof WindowEventMap>(
8
+ type: T,
9
+ listener: (this: Window, ev: WindowEventMap[T]) => void
10
+ ) => {
11
+ rootElement.addEventListener(type, listener);
12
+ };
13
+
14
+ export const dispatch = <T extends Event>(event: T) => {
15
+ rootElement.dispatchEvent(event);
16
+ };
@@ -0,0 +1,19 @@
1
+ const queue: { [key: string]: unknown[] } = {};
2
+
3
+ const add = (key: string, data: unknown): void => {
4
+ if (!queue[key]) {
5
+ queue[key] = [];
6
+ }
7
+ queue[key].push(data);
8
+ };
9
+
10
+ const getAll = (key: string) => {
11
+ const keyQueue = queue[key];
12
+ if (!keyQueue) {
13
+ return [];
14
+ }
15
+ delete queue[key];
16
+ return keyQueue;
17
+ };
18
+
19
+ export default { add, getAll };
@@ -0,0 +1,7 @@
1
+ export type UserAttributes = {
2
+ isLoggedIn?: boolean;
3
+ name?: string;
4
+ email?: string;
5
+ phone?: string;
6
+ trackingKey?: string;
7
+ };
@@ -0,0 +1,32 @@
1
+ import { fetchDataBasedOnAttributes } from './dataOrganizer';
2
+ import { dispatch, listen } from './eventHandler';
3
+ import { UserAttributes } from './types';
4
+
5
+ export enum AmediaUserEvents {
6
+ REQUEST_USER_ATTRIBUTES = 'amedia-user.request-user-attributes',
7
+ ON_USER_ATTRIBUTES_UPDATED = 'amedia-user.on-user-attributes-updated',
8
+ }
9
+
10
+ declare global {
11
+ interface WindowEventMap {
12
+ [AmediaUserEvents.REQUEST_USER_ATTRIBUTES]: CustomEvent<
13
+ Array<keyof UserAttributes>
14
+ >;
15
+ [AmediaUserEvents.ON_USER_ATTRIBUTES_UPDATED]: CustomEvent<UserAttributes>;
16
+ }
17
+ }
18
+
19
+ export const listenForUserAttributeRequests = () => {
20
+ listen(AmediaUserEvents.REQUEST_USER_ATTRIBUTES, (evt) => {
21
+ // Prevent other instances of this package from further processing
22
+ evt.stopImmediatePropagation();
23
+
24
+ dispatch(
25
+ new CustomEvent(AmediaUserEvents.ON_USER_ATTRIBUTES_UPDATED, {
26
+ detail: fetchDataBasedOnAttributes(evt.detail),
27
+ })
28
+ );
29
+ });
30
+ };
31
+
32
+ listenForUserAttributeRequests();
@@ -0,0 +1,36 @@
1
+ import { Record, Static } from 'runtypes';
2
+ import globalCache from '../lib/cache/global';
3
+ import { Engine } from '../lib/cache/types';
4
+
5
+ let cacheEngine: Engine;
6
+
7
+ export const setCacheEngine = (engine: Engine) => {
8
+ cacheEngine = engine;
9
+ };
10
+
11
+ const getCacheEngine = (): Engine => cacheEngine || globalCache;
12
+
13
+ const get = async <T extends Record<any, any>>(
14
+ key: string,
15
+ validator: T
16
+ ): Promise<Static<T> | void> => {
17
+ const data = await getCacheEngine().get(key);
18
+ if (!data) {
19
+ return Promise.resolve();
20
+ }
21
+ try {
22
+ const typedData = validator.check(data);
23
+ return typedData as T;
24
+ } catch (error) {
25
+ console.error('Failed validating data', { data, error });
26
+ getCacheEngine().remove(key);
27
+ return Promise.resolve();
28
+ }
29
+ };
30
+
31
+ const set = (key: string, value: unknown, expires: number) =>
32
+ getCacheEngine().set(key, value, expires);
33
+
34
+ const remove = (key: string): Promise<void> => getCacheEngine().remove(key);
35
+
36
+ export default { get, set, remove };
@@ -0,0 +1,148 @@
1
+ import fetch from 'jest-fetch-mock';
2
+ import {
3
+ checkForAccess,
4
+ getVstoken,
5
+ AccessFeatures,
6
+ CheckAccessForPaper,
7
+ GetVstoken,
8
+ GetNonUserAccess,
9
+ getNonUserAccess,
10
+ } from './jupiter';
11
+
12
+ beforeEach(() => {
13
+ fetch.resetMocks();
14
+ });
15
+
16
+ describe('/check_access_for_paper', () => {
17
+ const publicationDomain = 'www.rb.no';
18
+ const accessFeatures: AccessFeatures = ['newspaper'];
19
+
20
+ it('should check access for paper', async () => {
21
+ const response: CheckAccessForPaper = {
22
+ status: 'success',
23
+ access: 'granted',
24
+ publication: {
25
+ domain: 'www.rb.no',
26
+ id: 95,
27
+ },
28
+ access_features: ['amedia_staff', 'newspaper'],
29
+ };
30
+
31
+ fetch.mockResponseOnce(JSON.stringify(response));
32
+
33
+ await expect(
34
+ checkForAccess(publicationDomain, accessFeatures)
35
+ ).resolves.toEqual(response);
36
+ expect(fetch).toHaveBeenCalledWith(
37
+ `/api/jupiter/v1/check_access_for_paper/${publicationDomain}/?require=any&access_features=${accessFeatures.join(
38
+ ','
39
+ )}`
40
+ );
41
+ });
42
+
43
+ it('should deny access for user not logged in', async () => {
44
+ fetch.mockResponseOnce(JSON.stringify({ status: 'no_session_found' }), {
45
+ status: 400,
46
+ });
47
+
48
+ await expect(
49
+ checkForAccess(publicationDomain, accessFeatures)
50
+ ).rejects.toThrow('Request not ok (400: Bad Request).');
51
+ });
52
+
53
+ it('should fail on runtime validation', async () => {
54
+ fetch.mockResponseOnce(JSON.stringify({ access_features: 'foo' }));
55
+ console.error = jest.fn();
56
+
57
+ await expect(
58
+ checkForAccess(publicationDomain, accessFeatures)
59
+ ).rejects.toThrow(
60
+ 'Expected { status: "success"; access: "granted" | "denied"; publication: { id: number; domain: string; }; access_features: string[]; }, but was incompatible'
61
+ );
62
+ });
63
+ });
64
+
65
+ describe('/get_vstoken', () => {
66
+ const publicationDomain = 'www.rb.no';
67
+
68
+ it('should return vstoken', async () => {
69
+ const response: GetVstoken = {
70
+ status: 'success',
71
+ cookie: 'ofofb:16187:amedia_staff,newspaper,plussalt:cc2c2c:rb:jupiter',
72
+ access_features: ['newspaper', 'plussalt'],
73
+ };
74
+
75
+ fetch.mockResponseOnce(JSON.stringify(response));
76
+
77
+ await expect(getVstoken(publicationDomain)).resolves.toEqual(response);
78
+ expect(fetch).toHaveBeenCalledWith(
79
+ `/api/jupiter/v1/get_vstoken/${publicationDomain}`,
80
+ {
81
+ method: 'post',
82
+ }
83
+ );
84
+ });
85
+
86
+ it('should deny access for user not logged in', async () => {
87
+ fetch.mockResponseOnce(JSON.stringify({ status: 'no_session_found' }), {
88
+ status: 400,
89
+ });
90
+
91
+ await expect(getVstoken(publicationDomain)).rejects.toThrow(
92
+ 'Request not ok (400: Bad Request).'
93
+ );
94
+ });
95
+
96
+ it('should fail on runtime validation', async () => {
97
+ fetch.mockResponseOnce(JSON.stringify({ access_features: 'foo' }));
98
+ console.error = jest.fn();
99
+
100
+ await expect(getVstoken(publicationDomain)).rejects.toThrow(
101
+ 'Expected { status: "success"; cookie: string; access_features: string[]; }, but was incompatible'
102
+ );
103
+ });
104
+ });
105
+
106
+ describe('/non_user_access', () => {
107
+ const publicationDomain = 'www.rb.no';
108
+
109
+ it('should return none user access', async () => {
110
+ const response: GetNonUserAccess = {
111
+ status: 'success',
112
+ vstoken_cookie: 'd82ab3842a:2619693230:::rb:jupiter',
113
+ uuid: '',
114
+ access_features: [],
115
+ };
116
+
117
+ fetch.mockResponseOnce(JSON.stringify(response));
118
+
119
+ await expect(getNonUserAccess(publicationDomain)).resolves.toEqual(
120
+ response
121
+ );
122
+ expect(
123
+ fetch
124
+ ).toHaveBeenCalledWith(
125
+ `/api/jupiter/v1/non_user_access/${publicationDomain}`,
126
+ { method: 'post' }
127
+ );
128
+ });
129
+
130
+ it('should deny access for user not logged in', async () => {
131
+ fetch.mockResponseOnce(JSON.stringify({ status: 'no_session_found' }), {
132
+ status: 400,
133
+ });
134
+
135
+ await expect(getNonUserAccess(publicationDomain)).rejects.toThrow(
136
+ 'Request not ok (400: Bad Request).'
137
+ );
138
+ });
139
+
140
+ it('should fail on runtime validation', async () => {
141
+ fetch.mockResponseOnce(JSON.stringify({ vstoken_cookie: 3 }));
142
+ console.error = jest.fn();
143
+
144
+ await expect(getNonUserAccess(publicationDomain)).rejects.toThrow(
145
+ 'Expected { status: "success"; vstoken_cookie: string; uuid: string; access_features: string[]; }, but was incompatible'
146
+ );
147
+ });
148
+ });
@@ -0,0 +1,110 @@
1
+ import {
2
+ Array,
3
+ Literal,
4
+ Record,
5
+ Static,
6
+ String,
7
+ Number,
8
+ Union,
9
+ } from 'runtypes';
10
+
11
+ export type AccessFeatures = string[];
12
+
13
+ const PublicationSchema = Record({
14
+ id: Number,
15
+ domain: String,
16
+ });
17
+ export const CheckAccessForPaperSchema = Record({
18
+ status: Literal('success'),
19
+ access: Union(Literal('granted'), Literal('denied')),
20
+ publication: PublicationSchema,
21
+ access_features: Array(String),
22
+ });
23
+
24
+ export type CheckAccessForPaper = Static<typeof CheckAccessForPaperSchema>;
25
+
26
+ const GetVstokenSchema = Record({
27
+ status: Literal('success'),
28
+ cookie: String,
29
+ access_features: Array(String),
30
+ });
31
+
32
+ export type GetVstoken = Static<typeof GetVstokenSchema>;
33
+
34
+ const GetNonUserAccessSchema = Record({
35
+ status: Literal('success'),
36
+ vstoken_cookie: String,
37
+ uuid: String,
38
+ access_features: Array(String),
39
+ });
40
+
41
+ export type GetNonUserAccess = Static<typeof GetNonUserAccessSchema>;
42
+
43
+ export const checkForAccess = (
44
+ publicationDomain: string,
45
+ accessFeatures: AccessFeatures
46
+ ): Promise<CheckAccessForPaper> =>
47
+ fetch(
48
+ `/api/jupiter/v1/check_access_for_paper/${publicationDomain}/?require=any&access_features=${accessFeatures.join(
49
+ ','
50
+ )}`
51
+ )
52
+ .then((response) => {
53
+ if (!response.ok) {
54
+ // TODO Handle this.
55
+ throw new Error(
56
+ `Request not ok (${response.status}: ${response.statusText}).`
57
+ );
58
+ }
59
+ return response.json();
60
+ })
61
+ .then((json) => {
62
+ try {
63
+ return CheckAccessForPaperSchema.check(json);
64
+ } catch (error) {
65
+ console.error('Invalid schema', error);
66
+ throw error;
67
+ }
68
+ });
69
+
70
+ export const getVstoken = (publicationDomain: string): Promise<GetVstoken> =>
71
+ fetch(`/api/jupiter/v1/get_vstoken/${publicationDomain}`, { method: 'post' })
72
+ .then((response) => {
73
+ if (!response.ok) {
74
+ throw new Error(
75
+ `Request not ok (${response.status}: ${response.statusText}).`
76
+ );
77
+ }
78
+ return response.json();
79
+ })
80
+ .then((json) => {
81
+ try {
82
+ return GetVstokenSchema.check(json);
83
+ } catch (error) {
84
+ console.error('Invalid schema', error);
85
+ throw error;
86
+ }
87
+ });
88
+
89
+ export const getNonUserAccess = (
90
+ publicationDomain: string
91
+ ): Promise<GetNonUserAccess> =>
92
+ fetch(`/api/jupiter/v1/non_user_access/${publicationDomain}`, {
93
+ method: 'post',
94
+ })
95
+ .then((response) => {
96
+ if (!response.ok) {
97
+ throw new Error(
98
+ `Request not ok (${response.status}: ${response.statusText}).`
99
+ );
100
+ }
101
+ return response.json();
102
+ })
103
+ .then((json) => {
104
+ try {
105
+ return GetNonUserAccessSchema.check(json);
106
+ } catch (error) {
107
+ console.error('Invalid schema', error);
108
+ throw error;
109
+ }
110
+ });
@@ -0,0 +1,27 @@
1
+ /**
2
+ * @jest-environment jsdom
3
+ */
4
+
5
+ import fetch from 'jest-fetch-mock';
6
+ import backendLog from './mercury';
7
+
8
+ fetch.enableMocks();
9
+
10
+ beforeEach(() => {
11
+ fetch.resetMocks();
12
+ });
13
+
14
+ describe('Mercury backendlog', () => {
15
+ it('should include level in url', () => {
16
+ backendLog.error('jest message', {});
17
+ expect(fetch.mock.calls[0][0]).toContain('/error');
18
+ expect(fetch).toHaveBeenCalledTimes(1);
19
+ });
20
+
21
+ it('should include additional context as query parameters', () => {
22
+ backendLog.error('jest message', { referrer: 'https://www.rb.no/' });
23
+ const formData = fetch.mock.calls[0][1]?.body as FormData;
24
+
25
+ expect(formData?.get('referrer')).toEqual('https://www.rb.no/');
26
+ });
27
+ });
@@ -0,0 +1,47 @@
1
+ function postRequest(url: string, query: { [index: string]: any }) {
2
+ const body = new FormData();
3
+ Object.keys(query).forEach((key) => body.append(key, query[key]));
4
+ const options: RequestInit = {
5
+ credentials: 'include',
6
+ method: 'POST',
7
+ mode: 'cors',
8
+ body,
9
+ headers: {
10
+ 'Content-Type': 'application/x-www-form-urlencoded',
11
+ Accept: 'application/json',
12
+ },
13
+ };
14
+ fetch(url, options).then((res) => {
15
+ if (!res.ok) {
16
+ throw new Error(`Error, status: ${res.status}, text: ${res.statusText}`);
17
+ }
18
+ return res.json();
19
+ });
20
+ }
21
+
22
+ const backendLog = (
23
+ level: string,
24
+ message: string,
25
+ context: { [index: string]: any }
26
+ ) => {
27
+ const extendedContext = {
28
+ ...context,
29
+ message,
30
+ url: window.location.href,
31
+ domain: window.location.host,
32
+ };
33
+ postRequest(`//www.aid.no/api/mercury/v1/log/${level}`, extendedContext);
34
+ };
35
+
36
+ const log = {
37
+ error: (message: string, context: { [index: string]: any }) =>
38
+ backendLog('error', message, context),
39
+ warn: (message: string, context: { [index: string]: any }) =>
40
+ backendLog('warn', message, context),
41
+ info: (message: string, context: { [index: string]: any }) =>
42
+ backendLog('info', message, context),
43
+ debug: (message: string, context: { [index: string]: any }) =>
44
+ backendLog('debug', message, context),
45
+ };
46
+
47
+ export default log;
@@ -0,0 +1,34 @@
1
+ import { Optional, Record, Static, String } from 'runtypes';
2
+
3
+ export const SessionSchema = Record({
4
+ created_at: String,
5
+ updated_at: String,
6
+ user_uuid: String,
7
+ user_name: String,
8
+ tracking_key: String,
9
+ user_agent: Optional(String),
10
+
11
+ // @deprecated Use tracking_key
12
+ user_key: Optional(String),
13
+ });
14
+ export type Session = Static<typeof SessionSchema>;
15
+
16
+ export const getCurrentSession = async (): Promise<Session> =>
17
+ fetch(`/api/pluto/v1/sessions/current`)
18
+ .then((response) => {
19
+ if (!response.ok) {
20
+ // TODO Handle this.
21
+ throw new Error(
22
+ `Request not ok (${response.status}: ${response.statusText}).`
23
+ );
24
+ }
25
+ return response.json();
26
+ })
27
+ .then((json) => {
28
+ try {
29
+ return SessionSchema.check(json);
30
+ } catch (error) {
31
+ console.error('Invalid schema', error);
32
+ throw error;
33
+ }
34
+ });
@@ -0,0 +1,24 @@
1
+ {
2
+ "extends": "@amedia/eslint-config-typescript/tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "./dist/",
5
+ //"outFile": "./dist/amedia-user.js",
6
+ "rootDir": "./src",
7
+ "typeRoots": [
8
+ "./node_modules/@types"
9
+ ],
10
+ "module": "ES6",
11
+ //"module": "AMD",
12
+ "lib": [
13
+ "DOM"
14
+ ],
15
+ "declaration": true
16
+ },
17
+ "exclude": [
18
+ "node_modules",
19
+ "config",
20
+ ],
21
+ "include": [
22
+ "src/**/*",
23
+ ]
24
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "extends": "@amedia/eslint-config-typescript/tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "./dist/",
5
+ //"outFile": "./dist/amedia-user.js",
6
+ "rootDir": "./src",
7
+ "typeRoots": [
8
+ "./node_modules/@types"
9
+ ],
10
+ "module": "ES6",
11
+ //"module": "AMD",
12
+ "lib": [
13
+ "DOM"
14
+ ],
15
+ "declaration": true
16
+ },
17
+ "exclude": [
18
+ "node_modules",
19
+ "config",
20
+ "**/*.spec.ts"
21
+ ],
22
+ "include": [
23
+ "src/**/*",
24
+ ]
25
+ }