@opengis/fastify-table 1.0.8 → 1.0.9

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 (58) hide show
  1. package/.eslintrc.cjs +42 -42
  2. package/Changelog.md +47 -0
  3. package/README.md +26 -26
  4. package/config.js +11 -3
  5. package/crud/controllers/deleteCrud.js +10 -10
  6. package/crud/controllers/insert.js +28 -9
  7. package/crud/controllers/update.js +29 -10
  8. package/crud/controllers/utils/checkXSS.js +45 -0
  9. package/crud/controllers/utils/xssInjection.js +72 -0
  10. package/crud/funcs/dataDelete.js +15 -15
  11. package/crud/funcs/dataInsert.js +24 -24
  12. package/crud/funcs/getIdByToken.js +29 -0
  13. package/crud/funcs/isFileExists.js +13 -13
  14. package/crud/funcs/setTokenById.js +55 -0
  15. package/helper.js +28 -28
  16. package/index.js +32 -22
  17. package/package.json +22 -22
  18. package/pg/funcs/autoIndex.js +89 -89
  19. package/pg/funcs/getMeta.js +27 -27
  20. package/pg/funcs/init.js +42 -42
  21. package/pg/funcs/pgClients.js +2 -2
  22. package/pg/index.js +35 -35
  23. package/pg/pgClients.js +17 -17
  24. package/policy/funcs/checkPolicy.js +74 -0
  25. package/policy/funcs/sqlInjection.js +33 -0
  26. package/policy/index.js +14 -0
  27. package/redis/client.js +8 -8
  28. package/redis/funcs/redisClients.js +2 -2
  29. package/redis/index.js +19 -19
  30. package/server/templates/form/test.dataset.form.json +412 -0
  31. package/server.js +14 -14
  32. package/table/controllers/data.js +55 -55
  33. package/table/controllers/filter.js +24 -24
  34. package/table/controllers/form.js +10 -10
  35. package/table/controllers/suggest.js +60 -60
  36. package/table/controllers/utils/getSelect.js +20 -20
  37. package/table/controllers/utils/getSelectMeta.js +66 -66
  38. package/table/funcs/getFilterSQL/index.js +75 -75
  39. package/table/funcs/getFilterSQL/util/formatValue.js +142 -142
  40. package/table/funcs/getFilterSQL/util/getCustomQuery.js +13 -13
  41. package/table/funcs/getFilterSQL/util/getFilterQuery.js +73 -73
  42. package/table/funcs/getFilterSQL/util/getOptimizedQuery.js +12 -12
  43. package/table/funcs/getFilterSQL/util/getTableSql.js +34 -34
  44. package/table/index.js +14 -14
  45. package/test/api/crud.test.js +50 -48
  46. package/test/api/crud.xss.test.js +70 -0
  47. package/test/api/table.test.js +49 -49
  48. package/test/config.example +18 -18
  49. package/test/funcs/crud.test.js +77 -51
  50. package/test/funcs/pg.test.js +32 -32
  51. package/test/funcs/redis.test.js +19 -19
  52. package/test/funcs/table.test.js +48 -48
  53. package/test/templates/cls/test.json +9 -9
  54. package/test/templates/form/cp_building.form.json +32 -32
  55. package/test/templates/select/account_id.json +3 -3
  56. package/test/templates/select/storage.data.json +2 -2
  57. package/test/templates/table/gis.dataset.table.json +20 -20
  58. package/changelog.md +0 -26
package/.eslintrc.cjs CHANGED
@@ -1,42 +1,42 @@
1
- /* eslint-env node */
2
-
3
- module.exports = {
4
- env: {
5
- node: true,
6
- },
7
- root: true,
8
- extends: [
9
- 'eslint:recommended',
10
- 'airbnb-base',
11
-
12
- ],
13
- rules: {
14
- 'brace-style': [2, 'stroustrup', { allowSingleLine: true }],
15
- 'vue/max-attributes-per-line': 0,
16
- 'vue/valid-v-for': 0,
17
-
18
- // allow async-await
19
- 'generator-star-spacing': 'off',
20
-
21
- // allow paren-less arrow functions
22
- 'arrow-parens': 0,
23
- 'one-var': 0,
24
- 'max-len': 0,
25
- 'import/first': 0,
26
- 'import/named': 2,
27
- 'import/namespace': 2,
28
- 'import/default': 2,
29
- 'import/export': 2,
30
- 'import/extensions': 0,
31
- 'no-console': ['warn', { allow: ['warn', 'error'] }],
32
- 'import/no-unresolved': 0,
33
- 'import/no-extraneous-dependencies': 0,
34
- 'linebreak-style': ['error', 'unix'],
35
- // allow debugger during development
36
- 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
37
- },
38
-
39
- parserOptions: {
40
- ecmaVersion: 'latest',
41
- },
42
- };
1
+ /* eslint-env node */
2
+
3
+ module.exports = {
4
+ env: {
5
+ node: true,
6
+ },
7
+ root: true,
8
+ extends: [
9
+ 'eslint:recommended',
10
+ 'airbnb-base',
11
+
12
+ ],
13
+ rules: {
14
+ 'brace-style': [2, 'stroustrup', { allowSingleLine: true }],
15
+ 'vue/max-attributes-per-line': 0,
16
+ 'vue/valid-v-for': 0,
17
+
18
+ // allow async-await
19
+ 'generator-star-spacing': 'off',
20
+
21
+ // allow paren-less arrow functions
22
+ 'arrow-parens': 0,
23
+ 'one-var': 0,
24
+ 'max-len': 0,
25
+ 'import/first': 0,
26
+ 'import/named': 2,
27
+ 'import/namespace': 2,
28
+ 'import/default': 2,
29
+ 'import/export': 2,
30
+ 'import/extensions': 0,
31
+ 'no-console': ['warn', { allow: ['warn', 'error'] }],
32
+ 'import/no-unresolved': 0,
33
+ 'import/no-extraneous-dependencies': 0,
34
+ 'linebreak-style': ['error', 'unix'],
35
+ // allow debugger during development
36
+ 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
37
+ },
38
+
39
+ parserOptions: {
40
+ ecmaVersion: 'latest',
41
+ },
42
+ };
package/Changelog.md ADDED
@@ -0,0 +1,47 @@
1
+ # fastify-table
2
+
3
+ ## 1.0.9 - 29.04.2024
4
+
5
+ - crud token support
6
+ - security - xss restriction
7
+
8
+ ## 1.0.8 - 29.04.2024
9
+
10
+ - filter fix
11
+
12
+ ## 1.0.7 - 26.04.2024
13
+
14
+ - code optimization
15
+
16
+ ## 1.0.6 - 25.04.2024
17
+
18
+ - code optimization
19
+
20
+ ## 1.0.5 - 24.04.2024
21
+
22
+ - code optimization
23
+
24
+ ## 1.0.4 - 20.04.2024
25
+
26
+ - data api - order
27
+ - suggest api - db support
28
+ - del api fix
29
+
30
+ ## 1.0.3 - 17.04.2024
31
+
32
+ - fix unit test
33
+
34
+ ## 1.0.2 - 14.04.2024
35
+
36
+ - fix redis
37
+
38
+ ## 1.0.1 - 14.04.2024
39
+
40
+ - fix redis
41
+
42
+ ## 1.0.0 - 14.04.2024
43
+
44
+ - crud
45
+ - pg
46
+ - redis
47
+ - table
package/README.md CHANGED
@@ -1,26 +1,26 @@
1
- # fastify-table
2
-
3
- [![NPM version](https://img.shields.io/npm/v/@opengis/fastify-table)](https://www.npmjs.com/package/@opengis/fastify-table)
4
- [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](http://standardjs.com/)
5
-
6
- It standardizes the entire form building process, while taking care of everything from rendering to validation and processing:
7
-
8
- - pg
9
- - redis
10
- - crud
11
-
12
- ## Install
13
-
14
- ```bash
15
- npm i @opengis/fastify-table
16
- ```
17
-
18
- ## Usage
19
-
20
- ```js
21
- fastify.register(import('@opengis/fastify-table'), config);
22
- ```
23
-
24
- ## Documenation
25
-
26
- For a detailed understanding fastify-table, its features, and how to use them, refer to our [Documentation](https://apidocs.softpro.ua/gis.storage/).
1
+ # fastify-table
2
+
3
+ [![NPM version](https://img.shields.io/npm/v/@opengis/fastify-table)](https://www.npmjs.com/package/@opengis/fastify-table)
4
+ [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](http://standardjs.com/)
5
+
6
+ It standardizes the entire form building process, while taking care of everything from rendering to validation and processing:
7
+
8
+ - pg
9
+ - redis
10
+ - crud
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ npm i @opengis/fastify-table
16
+ ```
17
+
18
+ ## Usage
19
+
20
+ ```js
21
+ fastify.register(import('@opengis/fastify-table'), config);
22
+ ```
23
+
24
+ ## Documenation
25
+
26
+ For a detailed understanding fastify-table, its features, and how to use them, refer to our [Documentation](https://apidocs.softpro.ua/gis.storage/).
package/config.js CHANGED
@@ -1,3 +1,11 @@
1
- // import pg from './pg'
2
- const config = { allTemplates: {} };
3
- export default config;
1
+ import fs from 'fs';
2
+
3
+ const config = fs.existsSync('config.json')
4
+ ? JSON.parse(fs.readFileSync('config.json'))
5
+ : {};
6
+
7
+ Object.assign(config, {
8
+ allTemplates: config?.allTemplates || {},
9
+ });
10
+
11
+ export default config;
@@ -1,10 +1,10 @@
1
- import dataDelete from '../funcs/dataDelete.js';
2
-
3
- export default async function deleteCrud(req) {
4
- const { table, id } = req.params || {};
5
- if (!table) return { status: 404, message: 'table is required' };
6
-
7
- const data = await dataDelete({ table, id });
8
-
9
- return { rowCount: data.rowCount, msg: !data.rowCount ? data : null };
10
- }
1
+ import dataDelete from '../funcs/dataDelete.js';
2
+
3
+ export default async function deleteCrud(req) {
4
+ const { table, id } = req.params || {};
5
+ if (!table) return { status: 404, message: 'table is required' };
6
+
7
+ const data = await dataDelete({ table, id });
8
+
9
+ return { rowCount: data.rowCount, msg: !data.rowCount ? data : null };
10
+ }
@@ -1,9 +1,28 @@
1
- import dataInsert from '../funcs/dataInsert.js';
2
-
3
- export default async function insert(req) {
4
- const { table } = req.params || {};
5
- if (!table) return { status: 404, message: 'table is required' };
6
-
7
- const res = await dataInsert({ table, data: req.body });
8
- return res;
9
- }
1
+ import dataInsert from '../funcs/dataInsert.js';
2
+ import getIdByToken from '../funcs/getIdByToken.js';
3
+ import checkXSS from './utils/checkXSS.js';
4
+ import getTemplate from '../../table/controllers/utils/getTemplate.js';
5
+
6
+ export default async function insert(req) {
7
+ const { table } = req.params || {};
8
+ if (!table) return { status: 404, message: 'table is required' };
9
+
10
+ const { funcs, session, params } = req;
11
+ const tokenDataString = await getIdByToken({
12
+ funcs, session, token: params.table, mode: 'a', json: 0,
13
+ });
14
+
15
+ const { form, add } = JSON.parse(tokenDataString || '{}');
16
+
17
+ const formData = form ? await getTemplate('form', form) : {};
18
+
19
+ const xssCheck = checkXSS({ body: req.body, schema: formData?.schema });
20
+
21
+ if (xssCheck.error && formData?.xssCheck !== false) {
22
+ req.log.warn({ name: 'injection/xss', msg: xssCheck.error, table }, req);
23
+ return { message: 'Дані містять заборонені символи. Приберіть їх та спробуйте ще раз', status: 409 };
24
+ }
25
+
26
+ const res = await dataInsert({ table: add || table, data: req.body });
27
+ return res;
28
+ }
@@ -1,10 +1,29 @@
1
- import dataUpdate from '../funcs/dataUpdate.js';
2
-
3
- export default async function update(req) {
4
- const { table, id } = req.params || {};
5
- if (!table) return { status: 404, message: 'table is required' };
6
- if (!id) return { status: 404, message: 'id is required' };
7
-
8
- const res = await dataUpdate({ table, id, data: req.body });
9
- return res;
10
- }
1
+ import dataUpdate from '../funcs/dataUpdate.js';
2
+ import getIdByToken from '../funcs/getIdByToken.js';
3
+ import checkXSS from './utils/checkXSS.js';
4
+ import getTemplate from '../../table/controllers/utils/getTemplate.js';
5
+
6
+ export default async function update(req) {
7
+ const { table, id } = req.params || {};
8
+ if (!req.params?.table) return { message: 'table is required', status: 404 };
9
+ if (!id) return { message: 'id is required', status: 404 };
10
+
11
+ const { funcs, session, params } = req;
12
+ const tokenDataString = await getIdByToken({
13
+ funcs, session, token: params.table, mode: 'w', json: 0,
14
+ });
15
+
16
+ const tokenData = JSON.parse(tokenDataString || '{}');
17
+
18
+ const formData = tokenData?.form ? await getTemplate('form', tokenData.form) : {};
19
+
20
+ const xssCheck = checkXSS({ body: req.body, schema: formData?.schema });
21
+
22
+ if (xssCheck.error && formData?.xssCheck !== false) {
23
+ req.log.warn({ name: 'injection/xss', msg: xssCheck.error, table }, req);
24
+ return { message: 'Дані містять заборонені символи. Приберіть їх та спробуйте ще раз', status: 409 };
25
+ }
26
+
27
+ const res = await dataUpdate({ table: tokenData?.table || table, id: tokenData?.id || id, data: req.body });
28
+ return res;
29
+ }
@@ -0,0 +1,45 @@
1
+ /* import sqlInjection from '../../../policy/funcs/sqlInjection.js'; */
2
+ import xssInjection from './xssInjection.js';
3
+
4
+ /* const checkList = xssInjection.concat(sqlInjection); */
5
+
6
+ // RTE - rich text editor
7
+
8
+ function checkXSS({ body, schema = {} }) {
9
+ const data = typeof body === 'string' ? body : JSON.stringify(body);
10
+ const stopWords = xssInjection.filter((el) => data.toLowerCase().includes(el));
11
+
12
+ // check sql injection
13
+ const stopSpecialSymbols = data.match(/\p{S}OR\p{S}|\p{P}OR\p{P}| OR |\+OR\+/gi);
14
+ if (stopSpecialSymbols?.length) stopSpecialSymbols?.forEach((el) => stopWords.push(el));
15
+
16
+ // escape arrows on non-RTE
17
+ Object.keys(body)
18
+ .filter((key) => ['<', '>'].find((el) => body[key].includes(el))
19
+ && !['Summernote', 'Tiny', 'Ace'].includes(schema[key]?.type))
20
+ ?.forEach((key) => {
21
+ Object.assign(body, { [key]: body[key].replace(/</g, '&lt;').replace(/>/g, '&gt;') });
22
+ });
23
+ // try { } catch (err) { return { error: err.toString() }; }
24
+
25
+ if (!stopWords.length) return { body };
26
+
27
+ const disabledCheckFields = Object.keys(schema)?.filter((el) => schema[el]?.xssCheck === false); // exclude specific columns
28
+
29
+ // check RTE
30
+ /* const richTextFields = Object.keys(schema).filter((el) => ['Summernote', 'Tiny', 'Ace'].includes(schema[el]?.type));
31
+ richTextFields.filter((key) => !checkList.find((el) => body[key].includes(el)))?.forEach((key) => {
32
+ disabledCheckFields.push(key);
33
+ }); */
34
+
35
+ const field = Object.keys(body)
36
+ ?.find((key) => body[key]
37
+ && !disabledCheckFields.includes(key)
38
+ && body[key].toLowerCase().includes(stopWords[0]));
39
+ if (field) {
40
+ return { error: `rule: ${stopWords[0]} | attr: ${field} | val: ${body[field]}`, body };
41
+ }
42
+ return { body };
43
+ }
44
+
45
+ export default checkXSS;
@@ -0,0 +1,72 @@
1
+ const xssInjection = [
2
+ 'onkeypress=',
3
+ 'onkeyup=',
4
+ 'ondblclick=',
5
+ 'onerror=',
6
+ 'onmouseover=',
7
+ '<meta',
8
+ '<script',
9
+ 'vascript:',
10
+ 'onkeydown=',
11
+ 'onmousedown=',
12
+ 'onmouseenter=',
13
+ 'onmouseleave=',
14
+ 'onmousemove=',
15
+ 'onmouseout=',
16
+ 'onmouseup=',
17
+ 'onmousewheel=',
18
+ 'onpaste=',
19
+ 'onscroll=',
20
+ 'onwheel=',
21
+ 'javascript:',
22
+ '\\x',
23
+ 'eval(',
24
+ 'onmouseover=',
25
+ 'action=',
26
+ 'xlink:',
27
+ 'allowscriptaccess',
28
+ 'href=',
29
+ 'behavior:',
30
+ 'onreadystatechange=',
31
+ 'onstart=',
32
+ 'offline=',
33
+ 'onabort=',
34
+ 'onafterprint=',
35
+ 'onbeforeonload=',
36
+ 'onbeforeprint=',
37
+ 'onblur=',
38
+ 'oncanplay=',
39
+ 'oncanplaythrough=',
40
+ 'onchange=',
41
+ 'onclick=',
42
+ 'oncontextmenu=',
43
+ 'ondblclick=',
44
+ 'ondrag=',
45
+ 'ondragend=',
46
+ 'ondragenter=',
47
+ 'ondragleave=',
48
+ 'ondragover=',
49
+ 'ondragstart=',
50
+ 'ondrop=',
51
+ 'ondurationchange=',
52
+ 'onemptied=',
53
+ 'onended=',
54
+ 'onerror=',
55
+ 'onfocus=',
56
+ 'onformchange=',
57
+ 'onforminput=',
58
+ 'onhaschange=',
59
+ 'oninput=',
60
+ 'oninvalid=',
61
+ 'onkeydown=',
62
+ 'onkeypress=',
63
+ 'onkeyup=',
64
+ 'onload=',
65
+ 'onloadeddata=',
66
+ 'onloadedmetadata=',
67
+ 'onloadstart=',
68
+ 'alert(',
69
+ 'script:',
70
+ ];
71
+
72
+ export default xssInjection;
@@ -1,15 +1,15 @@
1
- import getPG from '../../pg/funcs/getPG.js';
2
-
3
- import getMeta from '../../pg/funcs/getMeta.js';
4
-
5
- export default async function dataDelete({
6
- table, id,
7
- }) {
8
- const pg = getPG({ name: 'client' });
9
- const { pk } = await getMeta(table);
10
- if (!pg.tlist.includes(table)) return 'table not exist';
11
- const delQuery = `delete from ${table} WHERE ${pk} = $1 returning *`;
12
- // console.log(updateDataset);
13
- const res = await pg.one(delQuery, [id]) || {};
14
- return res;
15
- }
1
+ import getPG from '../../pg/funcs/getPG.js';
2
+
3
+ import getMeta from '../../pg/funcs/getMeta.js';
4
+
5
+ export default async function dataDelete({
6
+ table, id,
7
+ }) {
8
+ const pg = getPG({ name: 'client' });
9
+ const { pk } = await getMeta(table);
10
+ if (!pg.tlist.includes(table)) return 'table not exist';
11
+ const delQuery = `delete from ${table} WHERE ${pk} = $1 returning *`;
12
+ // console.log(updateDataset);
13
+ const res = await pg.one(delQuery, [id]) || {};
14
+ return res;
15
+ }
@@ -1,24 +1,24 @@
1
- import getPG from '../../pg/funcs/getPG.js';
2
- import getMeta from '../../pg/funcs/getMeta.js';
3
-
4
- export default async function dataInsert({ table, data }) {
5
- const pg = getPG({ name: 'client' });
6
- if (!data) return null;
7
- const { columns } = await getMeta(table);
8
- if (!columns) return null;
9
-
10
- const names = columns.map((el) => el.name);
11
- const filterData = Object.keys(data)
12
- .filter((el) => data[el] && names.includes(el)).map((el) => [el, data[el]]);
13
-
14
- const insertQuery = `insert into ${table}
15
-
16
- ( ${filterData?.map((key) => `"${key[0]}"`).join(',')})
17
-
18
- values (${filterData?.map((key, i) => `$${i + 1}`).join(',')})
19
-
20
- returning *`;
21
- // console.log(updateDataset);
22
- const res = await pg.one(insertQuery, [...filterData.map((el) => (typeof el[1] === 'object' ? JSON.stringify(el[1]) : el[1]))]) || {};
23
- return res;
24
- }
1
+ import getPG from '../../pg/funcs/getPG.js';
2
+ import getMeta from '../../pg/funcs/getMeta.js';
3
+
4
+ export default async function dataInsert({ table, data }) {
5
+ const pg = getPG({ name: 'client' });
6
+ if (!data) return null;
7
+ const { columns } = await getMeta(table);
8
+ if (!columns) return null;
9
+
10
+ const names = columns.map((el) => el.name);
11
+ const filterData = Object.keys(data)
12
+ .filter((el) => data[el] && names.includes(el)).map((el) => [el, data[el]]);
13
+
14
+ const insertQuery = `insert into ${table}
15
+
16
+ ( ${filterData?.map((key) => `"${key[0]}"`).join(',')})
17
+
18
+ values (${filterData?.map((key, i) => `$${i + 1}`).join(',')})
19
+
20
+ returning *`;
21
+ await pg.query('DROP TRIGGER if exists dataset_before_update_insert ON gis.dataset');
22
+ const res = await pg.one(insertQuery, [...filterData.map((el) => (typeof el[1] === 'object' ? JSON.stringify(el[1]) : el[1]))]) || {};
23
+ return res;
24
+ }
@@ -0,0 +1,29 @@
1
+ import getRedis from '../../redis/funcs/getRedis.js';
2
+
3
+ function sprintf(str, ...args) {
4
+ return str.replace(/%s/g, () => args.shift());
5
+ }
6
+
7
+ const keys = {
8
+ r: '%s:token:view:%s',
9
+ a: '%s:token:add:%s',
10
+ w: '%s:token:edit:%s',
11
+ e: '%s:token:exec:%s',
12
+ };
13
+
14
+ async function getIdByToken({
15
+ funcs, session, token, mode = 'r', json,
16
+ }) {
17
+ if (mode === 'r') return token;
18
+
19
+ const { config } = funcs;
20
+ const { uid } = session?.passport?.user || (config.local ? { uid: '1' } : {});
21
+
22
+ const rclient2 = getRedis({ db: 2, funcs });
23
+
24
+ const key = sprintf(keys[mode], config?.pg?.database, uid);
25
+ const id = await rclient2.hget(key, token);
26
+ return json && id[0] === '{' ? JSON.parse(id) : id;
27
+ }
28
+
29
+ export default getIdByToken;
@@ -1,13 +1,13 @@
1
- import { access } from 'fs/promises';
2
-
3
- const isFileExists = async (filepath) => {
4
- try {
5
- await access(filepath);
6
- return true;
7
- }
8
- catch (err) {
9
- return false;
10
- }
11
- };
12
-
13
- export default isFileExists;
1
+ import { access } from 'fs/promises';
2
+
3
+ const isFileExists = async (filepath) => {
4
+ try {
5
+ await access(filepath);
6
+ return true;
7
+ }
8
+ catch (err) {
9
+ return false;
10
+ }
11
+ };
12
+
13
+ export default isFileExists;
@@ -0,0 +1,55 @@
1
+ import { createHash, randomUUID } from 'crypto';
2
+
3
+ import getRedis from '../../redis/funcs/getRedis.js';
4
+
5
+ const generateCodes = (ids, userToken) => {
6
+ const token = userToken || randomUUID();
7
+ const notNullIds = ids.filter((el) => el);
8
+ const obj = {};
9
+ const codes = notNullIds.reduce((acc, id) => {
10
+ const newToken = createHash('sha1').update(token + id).digest('base64url').replace(/-/g, '');
11
+ acc[newToken] = id; obj[id] = newToken;
12
+ return acc;
13
+ }, {});
14
+ return { codes, obj };
15
+ };
16
+
17
+ function setTokenById({
18
+ funcs, ids: idsOrigin, mode = 'r', session, referer, array,
19
+ }) {
20
+ const { config } = funcs;
21
+ const { uid } = session?.passport?.user || (config.local ? { uid: '1' } : {});
22
+
23
+ const rclient2 = getRedis({ db: 2, funcs });
24
+ const rclient5 = getRedis({ db: 5, funcs });
25
+
26
+ if (!uid) return { user: 'empty' };
27
+ if (!Object.keys(idsOrigin).length) return { ids: 'empty' };
28
+
29
+ const ids = idsOrigin.map((el) => (typeof el === 'object' ? JSON.stringify(el) : el));
30
+ // update/delete
31
+
32
+ if (mode === 'r') return null;
33
+
34
+ // TODO generate salt
35
+ const { codes, obj } = generateCodes(ids, uid);
36
+
37
+ if (!Object.keys(codes).length) return { ids: 'empty' };
38
+
39
+ rclient2.hmset(`${config.pg.database}:token:${{
40
+ e: 'exec', r: 'view', w: 'edit', a: 'add',
41
+ }[mode]}:${uid}`, codes);
42
+
43
+ // log token for debug. add extra data - uid, mode, date
44
+ const dt = new Date().toISOString();
45
+ const codesLog = Object.keys(codes).reduce((acc, key) => {
46
+ acc[key] = `{"referer": "${referer}" ,"uid":"${uid}","mode":"${mode}","date":"${dt}",${codes[key].substr(1)}`;
47
+ return acc;
48
+ }, {});
49
+ rclient5.hmset(`${config.pg.database}:token:edit`, codesLog); // 'EX', 64800
50
+
51
+ // TODO дополнительно писать в hset token -> uid
52
+ return array ? Object.values(obj) : obj;
53
+ }
54
+
55
+ export default setTokenById;
package/helper.js CHANGED
@@ -1,28 +1,28 @@
1
- // This file contains code that we reuse
2
- // between our tests.
3
- import Fastify from 'fastify';
4
- import config from './test/config.js';
5
- import appService from './index.js';
6
-
7
- import rclient from './redis/client.js';
8
- import pgClients from './pg/pgClients.js';
9
-
10
- // automatically build and tear down our instance
11
- async function build(t) {
12
- // you can set all the options supported by the fastify CLI command
13
- // const argv = [AppPath]
14
- process.env.NODE_ENV = 'production';
15
- const app = Fastify({ logger: false });
16
- app.register(appService, config);
17
- // close the app after we are done
18
- t.after(() => {
19
- // console.log('close app');
20
- pgClients.client.end();
21
- rclient.quit();
22
- app.close();
23
- });
24
-
25
- return app;
26
- }
27
-
28
- export default build;
1
+ // This file contains code that we reuse
2
+ // between our tests.
3
+ import Fastify from 'fastify';
4
+ import config from './test/config.js';
5
+ import appService from './index.js';
6
+
7
+ import rclient from './redis/client.js';
8
+ import pgClients from './pg/pgClients.js';
9
+
10
+ // automatically build and tear down our instance
11
+ async function build(t) {
12
+ // you can set all the options supported by the fastify CLI command
13
+ // const argv = [AppPath]
14
+ process.env.NODE_ENV = 'production';
15
+ const app = Fastify({ logger: false });
16
+ app.register(appService, config);
17
+ // close the app after we are done
18
+ t.after(() => {
19
+ // console.log('close app');
20
+ pgClients.client.end();
21
+ rclient.quit();
22
+ app.close();
23
+ });
24
+
25
+ return app;
26
+ }
27
+
28
+ export default build;