@opengis/fastify-table 1.0.73 → 1.0.75

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 (96) hide show
  1. package/.eslintrc.cjs +42 -42
  2. package/Changelog.md +233 -229
  3. package/README.md +26 -26
  4. package/config.js +10 -10
  5. package/cron/controllers/cronApi.js +22 -22
  6. package/cron/controllers/utils/cronList.js +1 -1
  7. package/cron/funcs/addCron.js +131 -131
  8. package/cron/index.js +10 -10
  9. package/crud/controllers/deleteCrud.js +19 -14
  10. package/crud/controllers/insert.js +54 -48
  11. package/crud/controllers/update.js +59 -54
  12. package/crud/controllers/utils/checkXSS.js +45 -45
  13. package/crud/controllers/utils/xssInjection.js +72 -72
  14. package/crud/funcs/dataDelete.js +15 -15
  15. package/crud/funcs/dataInsert.js +24 -24
  16. package/crud/funcs/dataUpdate.js +24 -24
  17. package/crud/funcs/getAccess.js +53 -0
  18. package/crud/funcs/getOpt.js +10 -10
  19. package/crud/funcs/getToken.js +27 -27
  20. package/crud/funcs/isFileExists.js +13 -13
  21. package/crud/funcs/setOpt.js +16 -16
  22. package/crud/funcs/setToken.js +53 -53
  23. package/crud/index.js +36 -27
  24. package/helper.js +28 -28
  25. package/index.js +97 -97
  26. package/migration/exec.migrations.js +75 -75
  27. package/notification/controllers/testEmail.js +49 -49
  28. package/notification/controllers/userNotifications.js +19 -19
  29. package/notification/funcs/addNotification.js +8 -8
  30. package/notification/funcs/sendNotification.js +111 -111
  31. package/notification/funcs/utils/sendEmail.js +39 -39
  32. package/notification/index.js +38 -31
  33. package/package.json +26 -26
  34. package/pg/funcs/getPG.js +30 -30
  35. package/pg/pgClients.js +20 -20
  36. package/policy/funcs/checkPolicy.js +82 -82
  37. package/policy/funcs/sqlInjection.js +33 -33
  38. package/policy/index.js +14 -14
  39. package/redis/client.js +8 -8
  40. package/redis/funcs/getRedis.js +23 -23
  41. package/redis/funcs/redisClients.js +2 -2
  42. package/redis/index.js +19 -19
  43. package/server/migrations/0.sql +64 -13
  44. package/server/migrations/crm.sql +150 -150
  45. package/server/migrations/log.sql +43 -43
  46. package/server/templates/form/test.dataset.form.json +411 -411
  47. package/server/templates/select/test.storage.data.json +2 -2
  48. package/server/templates/table/test.dataset.table.json +24 -24
  49. package/server/templates/table/test.gis.map.table.json +45 -0
  50. package/server.js +14 -14
  51. package/table/controllers/card.js +44 -44
  52. package/table/controllers/data.js +95 -94
  53. package/table/controllers/filter.js +37 -37
  54. package/table/controllers/form.js +28 -28
  55. package/table/controllers/search.js +72 -72
  56. package/table/controllers/suggest.js +62 -61
  57. package/table/controllers/table.js +44 -44
  58. package/table/controllers/utils/getSelect.js +20 -20
  59. package/table/controllers/utils/getSelectMeta.js +66 -66
  60. package/table/controllers/utils/getTemplate.js +28 -28
  61. package/table/controllers/utils/getTemplates.js +18 -18
  62. package/table/controllers/utils/gisIRColumn.js +68 -68
  63. package/table/funcs/getFilterSQL/index.js +75 -75
  64. package/table/funcs/getFilterSQL/util/formatValue.js +142 -142
  65. package/table/funcs/getFilterSQL/util/getCustomQuery.js +13 -13
  66. package/table/funcs/getFilterSQL/util/getFilterQuery.js +73 -73
  67. package/table/funcs/getFilterSQL/util/getOptimizedQuery.js +12 -12
  68. package/table/funcs/getFilterSQL/util/getTableSql.js +34 -34
  69. package/table/funcs/metaFormat/getSelectVal.js +20 -20
  70. package/table/funcs/metaFormat/index.js +27 -27
  71. package/table/index.js +78 -46
  72. package/test/api/crud.test.js +88 -76
  73. package/test/api/crud.xss.test.js +72 -71
  74. package/test/api/notification.test.js +37 -37
  75. package/test/api/table.test.js +57 -57
  76. package/test/api/widget.test.js +114 -114
  77. package/test/config.example +18 -18
  78. package/test/funcs/crud.test.js +76 -76
  79. package/test/funcs/notification.test.js +31 -31
  80. package/test/funcs/pg.test.js +34 -34
  81. package/test/funcs/redis.test.js +19 -19
  82. package/test/templates/cls/test.json +9 -9
  83. package/test/templates/form/cp_building.form.json +32 -32
  84. package/test/templates/select/account_id.json +3 -3
  85. package/test/templates/select/storage.data.json +2 -2
  86. package/test/templates/table/gis.dataset.table.json +20 -20
  87. package/util/controllers/next.id.js +4 -4
  88. package/util/controllers/properties.add.js +50 -50
  89. package/util/controllers/properties.get.js +19 -19
  90. package/util/index.js +20 -13
  91. package/widget/controllers/utils/historyFormat.js +76 -76
  92. package/widget/controllers/utils/obj2db.js +13 -13
  93. package/widget/controllers/widget.del.js +44 -44
  94. package/widget/controllers/widget.get.js +96 -96
  95. package/widget/controllers/widget.set.js +70 -70
  96. package/widget/index.js +40 -29
@@ -1,72 +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
+ 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, pg: pg1,
7
- }) {
8
- const pg = pg1 || 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, pg: pg1,
7
+ }) {
8
+ const pg = pg1 || 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, pg: pg1 }) {
5
- const pg = pg1 || 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) => (key[0] === 'geom' ? `st_setsrid(st_geomfromgeojson($${i + 1}::json),4326)` : `$${i + 1}`)).join(',')})
19
-
20
- returning *`;
21
-
22
- const res = await pg.query(insertQuery, [...filterData.map((el) => (typeof el[1] === 'object' && (!Array.isArray(el[1]) || typeof el[1]?.[0] === '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, pg: pg1 }) {
5
+ const pg = pg1 || 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) => (key[0] === 'geom' ? `st_setsrid(st_geomfromgeojson($${i + 1}::json),4326)` : `$${i + 1}`)).join(',')})
19
+
20
+ returning *`;
21
+
22
+ const res = await pg.query(insertQuery, [...filterData.map((el) => (typeof el[1] === 'object' && (!Array.isArray(el[1]) || typeof el[1]?.[0] === 'object') ? JSON.stringify(el[1]) : el[1]))]) || {};
23
+ return res;
24
+ }
@@ -1,24 +1,24 @@
1
- import getPG from '../../pg/funcs/getPG.js';
2
-
3
- import getMeta from '../../pg/funcs/getMeta.js';
4
-
5
- export default async function dataUpdate({
6
- table, id, data, pg: pg1,
7
- }) {
8
- if (!data || !table || !id) return null;
9
-
10
- const pg = pg1 || getPG({ name: 'client' });
11
- const { columns, pk } = await getMeta(table);
12
-
13
- const names = columns?.map((el) => el.name);
14
- const filterData = Object.keys(data)
15
- .filter((el) => (typeof data[el] === 'boolean' ? true : data[el] && names?.includes(el)));
16
-
17
- const filterValue = filterData.map((el) => [el, data[el]]).map((el) => (typeof el[1] === 'object' && (!Array.isArray(el[1]) || typeof el[1]?.[0] === 'object') ? JSON.stringify(el[1]) : el[1]));
18
-
19
- const updateQuery = `UPDATE ${table} SET ${filterData?.map((key, i) => (key === 'geom' ? `"${key}"=st_setsrid(st_geomfromgeojson($${i + 2}::json),4326)` : `"${key}"=$${i + 2}`)).join(',')}
20
- WHERE ${pk} = $1 returning *`;
21
- // console.log(updateDataset);
22
- const res = await pg.query(updateQuery, [id, ...filterValue]).then(el => el?.rows?.[0]) || {};
23
- return res;
24
- }
1
+ import getPG from '../../pg/funcs/getPG.js';
2
+
3
+ import getMeta from '../../pg/funcs/getMeta.js';
4
+
5
+ export default async function dataUpdate({
6
+ table, id, data, pg: pg1,
7
+ }) {
8
+ if (!data || !table || !id) return null;
9
+
10
+ const pg = pg1 || getPG({ name: 'client' });
11
+ const { columns, pk } = await getMeta(table);
12
+
13
+ const names = columns?.map((el) => el.name);
14
+ const filterData = Object.keys(data)
15
+ .filter((el) => (typeof data[el] === 'boolean' ? true : data[el] && names?.includes(el)));
16
+
17
+ const filterValue = filterData.map((el) => [el, data[el]]).map((el) => (typeof el[1] === 'object' && (!Array.isArray(el[1]) || typeof el[1]?.[0] === 'object') ? JSON.stringify(el[1]) : el[1]));
18
+
19
+ const updateQuery = `UPDATE ${table} SET ${filterData?.map((key, i) => (key === 'geom' ? `"${key}"=st_setsrid(st_geomfromgeojson($${i + 2}::json),4326)` : `"${key}"=$${i + 2}`)).join(',')}
20
+ WHERE ${pk} = $1 returning *`;
21
+ // console.log(updateDataset);
22
+ const res = await pg.query(updateQuery, [id, ...filterValue]).then(el => el?.rows?.[0]) || {};
23
+ return res;
24
+ }
@@ -0,0 +1,53 @@
1
+ import getMeta from '../../pg/funcs/getMeta.js';
2
+ import getTemplate from '../../table/controllers/utils/getTemplate.js';
3
+ import config from '../../config.js';
4
+
5
+ const q = `select a.route_id as id, b.actions, b.scope
6
+ from admin.routes a
7
+ left join admin.access b on
8
+ a.route_id=b.route_id
9
+ left join admin.roles c on
10
+ b.role_id=c.role_id
11
+ and c.enabled
12
+ left join admin.user_roles d on
13
+ c.role_id=d.role_id
14
+ and ( case when
15
+ d.expiration is not null
16
+ then d.expiration > CURRENT_DATE
17
+ else 1=1
18
+ end )
19
+ where a.route_id=$1 and $2 in (b.user_uid, d.user_uid)`;
20
+
21
+ export default async function getAccess(req, template, id = null) {
22
+ if (config.disableAccessRestriction || true) {
23
+ return { actions: ['get', 'edit', 'del'], my: true, query: '1=1' };
24
+ }
25
+ const { pg, session = {} } = req;
26
+ const { uid, user_type: userType } = session.passport?.user || {};
27
+ if (!uid || !template) return null;
28
+
29
+ if (!pg.pk?.['admin.access']) return null;
30
+
31
+ const { table } = await getTemplate('table', template) || {};
32
+ if (!table) return null;
33
+
34
+ const { scope = 'my', actions = [] } = await pg.one(q, [template, uid]);
35
+ // console.log(scope, actions);
36
+
37
+ const { columns = [] } = await getMeta(table);
38
+ const columnList = columns.map((el) => el.name || el).join(',');
39
+
40
+ const query = userType?.includes('admin') ? '1=1' : {
41
+ my: `uid='${uid}'`,
42
+ responsible: columnList.includes('responsible_id')
43
+ ? `responsible_id='${uid}'`
44
+ : `uid='${uid}'`,
45
+ all: '1=1',
46
+ }[scope];
47
+
48
+ const { my } = pg.pk?.[table] && id ? await pg.one(`select uid=$1 as my from ${table} where ${pg.pk?.[table]}=$2`, [uid, id]) : {};
49
+
50
+ return {
51
+ scope, actions, query, my,
52
+ };
53
+ }
@@ -1,10 +1,10 @@
1
- import getRedis from '../../redis/funcs/getRedis.js';
2
-
3
- export default async function getOpt(token, funcs) {
4
- const rclient = getRedis({ db: 0, funcs });
5
-
6
- const key = `opt:${token}`;
7
- const data = await rclient.get(key);
8
- if (!data) return null;
9
- return JSON.parse(data);
10
- }
1
+ import getRedis from '../../redis/funcs/getRedis.js';
2
+
3
+ export default async function getOpt(token, funcs) {
4
+ const rclient = getRedis({ db: 0, funcs });
5
+
6
+ const key = `opt:${token}`;
7
+ const data = await rclient.get(key);
8
+ if (!data) return null;
9
+ return JSON.parse(data);
10
+ }
@@ -1,27 +1,27 @@
1
- import getRedis from '../../redis/funcs/getRedis.js';
2
- import config from '../../config.js';
3
-
4
- function sprintf(str, ...args) {
5
- return str.replace(/%s/g, () => args.shift());
6
- }
7
-
8
- const keys = {
9
- r: '%s:token:view:%s',
10
- a: '%s:token:add:%s',
11
- w: '%s:token:edit:%s',
12
- e: '%s:token:exec:%s',
13
- };
14
-
15
- async function getToken({
16
- uid, token, mode = 'r', json,
17
- }) {
18
- if (mode === 'r') return token;
19
-
20
- const rclient = getRedis({ db: 0 });
21
-
22
- const key = sprintf(keys[mode], config?.pg?.database, uid?.toString());
23
- const id = await rclient.hget(key, token);
24
- return json && id?.[0] === '{' ? JSON.parse(id) : id;
25
- }
26
-
27
- export default getToken;
1
+ import getRedis from '../../redis/funcs/getRedis.js';
2
+ import config from '../../config.js';
3
+
4
+ function sprintf(str, ...args) {
5
+ return str.replace(/%s/g, () => args.shift());
6
+ }
7
+
8
+ const keys = {
9
+ r: '%s:token:view:%s',
10
+ a: '%s:token:add:%s',
11
+ w: '%s:token:edit:%s',
12
+ e: '%s:token:exec:%s',
13
+ };
14
+
15
+ async function getToken({
16
+ uid, token, mode = 'r', json,
17
+ }) {
18
+ if (mode === 'r') return token;
19
+
20
+ const rclient = getRedis({ db: 0 });
21
+
22
+ const key = sprintf(keys[mode], config?.pg?.database, uid?.toString());
23
+ const id = await rclient.hget(key, token);
24
+ return json && id?.[0] === '{' ? JSON.parse(id) : id;
25
+ }
26
+
27
+ export default getToken;
@@ -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;
@@ -1,16 +1,16 @@
1
- import { createHash } from 'crypto';
2
- import getRedis from '../../redis/funcs/getRedis.js';
3
-
4
- function md5(string) {
5
- return createHash('md5').update(string).digest('hex');
6
- }
7
-
8
- export default async function setOpt(params) {
9
- const token = Buffer.from(md5(typeof params === 'object' ? JSON.stringify(params) : params), 'hex').toString('base64').replace(/[+-=]+/g, '');
10
- // const token = md5(params);
11
- const key = `opt:${token}`;
12
-
13
- const rclient = getRedis({ db: 0, funcs: params.funcs });
14
- await rclient.set(key, JSON.stringify(params), 'EX', 60 * 60);
15
- return token;
16
- }
1
+ import { createHash } from 'crypto';
2
+ import getRedis from '../../redis/funcs/getRedis.js';
3
+
4
+ function md5(string) {
5
+ return createHash('md5').update(string).digest('hex');
6
+ }
7
+
8
+ export default async function setOpt(params) {
9
+ const token = Buffer.from(md5(typeof params === 'object' ? JSON.stringify(params) : params), 'hex').toString('base64').replace(/[+-=]+/g, '');
10
+ // const token = md5(params);
11
+ const key = `opt:${token}`;
12
+
13
+ const rclient = getRedis({ db: 0, funcs: params.funcs });
14
+ await rclient.set(key, JSON.stringify(params), 'EX', 60 * 60);
15
+ return token;
16
+ }
@@ -1,53 +1,53 @@
1
- import { createHash, randomUUID } from 'crypto';
2
-
3
- import config from '../../config.js';
4
- import getRedis from '../../redis/funcs/getRedis.js';
5
-
6
- const generateCodes = (ids, userToken) => {
7
- const token = userToken || randomUUID();
8
- const notNullIds = ids.filter((el) => el);
9
- const obj = {};
10
- const codes = notNullIds.reduce((acc, id) => {
11
- const newToken = createHash('sha1').update(token + id).digest('base64url').replace(/-/g, '');
12
- acc[newToken] = id; obj[id] = newToken;
13
- return acc;
14
- }, {});
15
- return { codes, obj };
16
- };
17
-
18
- function setToken({
19
- ids: idsOrigin, mode = 'r', uid, referer, array,
20
- }) {
21
- const rclient2 = getRedis({ db: 0 });
22
- // const rclient5 = getRedis({ db: 0, funcs });
23
-
24
- if (!uid) return { user: 'empty' };
25
- if (!Object.keys(idsOrigin).length) return { ids: 'empty' };
26
-
27
- const ids = idsOrigin.map((el) => (typeof el === 'object' ? JSON.stringify(el) : el));
28
- // update/delete
29
-
30
- if (mode === 'r') return null;
31
-
32
- // TODO generate salt
33
- const { codes, obj } = generateCodes(ids, uid);
34
-
35
- if (!Object.keys(codes).length) return { ids: 'empty' };
36
-
37
- rclient2.hmset(`${config.pg.database}:token:${{
38
- e: 'exec', r: 'view', w: 'edit', a: 'add',
39
- }[mode]}:${uid}`, codes);
40
-
41
- // log token for debug. add extra data - uid, mode, date
42
- /* const dt = new Date().toISOString();
43
- const codesLog = Object.keys(codes).reduce((acc, key) => {
44
- acc[key] = `{"referer": "${referer}" ,"uid":"${uid}","mode":"${mode}","date":"${dt}",${codes[key].substr(1)}`;
45
- return acc;
46
- }, {});
47
- rclient5.hmset(`${config.pg.database}:token:edit`, codesLog); // 'EX', 64800 */
48
-
49
- // TODO дополнительно писать в hset token -> uid
50
- return array ? Object.values(obj) : obj;
51
- }
52
-
53
- export default setToken;
1
+ import { createHash, randomUUID } from 'crypto';
2
+
3
+ import config from '../../config.js';
4
+ import getRedis from '../../redis/funcs/getRedis.js';
5
+
6
+ const generateCodes = (ids, userToken) => {
7
+ const token = userToken || randomUUID();
8
+ const notNullIds = ids.filter((el) => el);
9
+ const obj = {};
10
+ const codes = notNullIds.reduce((acc, id) => {
11
+ const newToken = createHash('sha1').update(token + id).digest('base64url').replace(/-/g, '');
12
+ acc[newToken] = id; obj[id] = newToken;
13
+ return acc;
14
+ }, {});
15
+ return { codes, obj };
16
+ };
17
+
18
+ function setToken({
19
+ ids: idsOrigin, mode = 'r', uid, referer, array,
20
+ }) {
21
+ const rclient2 = getRedis({ db: 0 });
22
+ // const rclient5 = getRedis({ db: 0, funcs });
23
+
24
+ if (!uid) return { user: 'empty' };
25
+ if (!Object.keys(idsOrigin).length) return { ids: 'empty' };
26
+
27
+ const ids = idsOrigin.map((el) => (typeof el === 'object' ? JSON.stringify(el) : el));
28
+ // update/delete
29
+
30
+ if (mode === 'r') return null;
31
+
32
+ // TODO generate salt
33
+ const { codes, obj } = generateCodes(ids, uid);
34
+
35
+ if (!Object.keys(codes).length) return { ids: 'empty' };
36
+
37
+ rclient2.hmset(`${config.pg.database}:token:${{
38
+ e: 'exec', r: 'view', w: 'edit', a: 'add',
39
+ }[mode]}:${uid}`, codes);
40
+
41
+ // log token for debug. add extra data - uid, mode, date
42
+ /* const dt = new Date().toISOString();
43
+ const codesLog = Object.keys(codes).reduce((acc, key) => {
44
+ acc[key] = `{"referer": "${referer}" ,"uid":"${uid}","mode":"${mode}","date":"${dt}",${codes[key].substr(1)}`;
45
+ return acc;
46
+ }, {});
47
+ rclient5.hmset(`${config.pg.database}:token:edit`, codesLog); // 'EX', 64800 */
48
+
49
+ // TODO дополнительно писать в hset token -> uid
50
+ return array ? Object.values(obj) : obj;
51
+ }
52
+
53
+ export default setToken;
package/crud/index.js CHANGED
@@ -1,27 +1,36 @@
1
- import getOpt from './funcs/getOpt.js';
2
- import setOpt from './funcs/setOpt.js';
3
- import isFileExists from './funcs/isFileExists.js';
4
- import dataUpdate from './funcs/dataUpdate.js';
5
- import dataInsert from './funcs/dataInsert.js';
6
-
7
- import update from './controllers/update.js';
8
- import insert from './controllers/insert.js';
9
- import deleteCrud from './controllers/deleteCrud.js';
10
-
11
- async function plugin(fastify, config = {}) {
12
- const prefix = config.prefix || '/api';
13
- // funcs
14
- fastify.decorate('setOpt', setOpt);
15
- fastify.decorate('getOpt', getOpt);
16
- fastify.decorate('dataUpdate', dataUpdate);
17
- fastify.decorate('dataInsert', dataInsert);
18
-
19
- fastify.decorate('isFileExists', isFileExists);
20
-
21
- // api
22
- fastify.put(`${prefix}/table/:table/:id`, {}, update);
23
- fastify.delete(`${prefix}/table/:table/:id`, {}, deleteCrud);
24
- fastify.post(`${prefix}/table/:table`, {}, insert);
25
- }
26
-
27
- export default plugin;
1
+ import getOpt from './funcs/getOpt.js';
2
+ import setOpt from './funcs/setOpt.js';
3
+ import isFileExists from './funcs/isFileExists.js';
4
+ import dataUpdate from './funcs/dataUpdate.js';
5
+ import dataInsert from './funcs/dataInsert.js';
6
+
7
+ import update from './controllers/update.js';
8
+ import insert from './controllers/insert.js';
9
+ import deleteCrud from './controllers/deleteCrud.js';
10
+ import getAccessFunc from './funcs/getAccess.js';
11
+
12
+ const tableSchema = {
13
+ params: {
14
+ id: { type: 'string', pattern: '^([\\d\\w]+)$' },
15
+ table: { type: 'string', pattern: '^([\\w\\d_.]+)$' },
16
+ },
17
+ };
18
+
19
+ async function plugin(fastify, config = {}) {
20
+ const prefix = config.prefix || '/api';
21
+ // funcs
22
+ fastify.decorate('setOpt', setOpt);
23
+ fastify.decorate('getOpt', getOpt);
24
+ fastify.decorate('dataUpdate', dataUpdate);
25
+ fastify.decorate('dataInsert', dataInsert);
26
+ fastify.decorate('getAccess', getAccessFunc);
27
+
28
+ fastify.decorate('isFileExists', isFileExists);
29
+
30
+ // api
31
+ fastify.put(`${prefix}/table/:table/:id`, { schema: tableSchema }, update);
32
+ fastify.delete(`${prefix}/table/:table/:id`, { schema: tableSchema }, deleteCrud);
33
+ fastify.post(`${prefix}/table/:table`, { schema: tableSchema }, insert);
34
+ }
35
+
36
+ export default plugin;