@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,131 +1,131 @@
1
- import { createHash } from 'crypto';
2
-
3
- import cronList from '../controllers/utils/cronList.js';
4
- import getRedis from '../../redis/funcs/getRedis.js';
5
- import getPG from '../../pg/funcs/getPG.js';
6
-
7
- const md5 = (string) => createHash('md5').update(string).digest('hex');
8
-
9
- async function verifyUnique(name, config, rclient) {
10
- const cronId = config.port || 3000 + md5(name);
11
- // one per node check
12
- const key = `cron:unique:${cronId}`;
13
- const unique = await rclient.setnx(key, 1);
14
- const ttl = await rclient.ttl(key);
15
- if (!unique && ttl !== -1) {
16
- return false;
17
- }
18
- await rclient.expire(key, 20);
19
- return true;
20
- }
21
-
22
- const intervalStringMs = {
23
- everyMin: 1000 * 60,
24
- tenMin: 1000 * 60 * 10,
25
- everyHour: 1000 * 60 * 60,
26
- isHalfday: 1000 * 60 * 60 * 12,
27
- dailyHour: 1000 * 60 * 60 * 24,
28
- };
29
-
30
- const interval2ms = {
31
- string: (interval) => {
32
- const date = new Date();
33
- const intervarSplit = interval.match(/^(\*{2}|(\*)?(\d{1,2})):(\*(\d)|(\d{2}))/);
34
- if (!intervarSplit) {
35
- throw new Error(`interval ${interval} not suported`);
36
- }
37
- const [, , isHalfday, dailyHour, , tenMin, HourlyMin] = intervarSplit;
38
- const intervalMs = (isHalfday && intervalStringMs.isHalfday)
39
- || (dailyHour && intervalStringMs.dailyHour)
40
- || (tenMin && intervalStringMs.tenMin)
41
- || intervalStringMs.everyHour;
42
- const offsetDay = ((+dailyHour || 0) * 60 + (+tenMin || +HourlyMin)) * 60 * 1000;
43
- const offsetCur = (date - date.getTimezoneOffset() * 1000 * 60) % intervalMs;
44
- const waitMs = (offsetDay - offsetCur + intervalMs) % intervalMs;
45
- return [waitMs, intervalMs];
46
- },
47
- number: (interval) => {
48
- const date = new Date();
49
- const intervalMs = interval * 1000;
50
- const dateWithTZ = date - date.getTimezoneOffset() * 1000 * 60;
51
- const offsetCur = dateWithTZ % intervalMs;
52
- // start every cron within 1 hour
53
- const sixtyMinutesStartMs = 3600000;
54
- const waitMs = (intervalMs - offsetCur) % sixtyMinutesStartMs;
55
- return [waitMs, intervalMs];
56
- },
57
- };
58
-
59
- async function runCron({
60
- pg, funcs, func, name, rclient, log,
61
- }) {
62
- const unique = await verifyUnique(name, funcs.config, rclient);
63
-
64
- if (!unique) return;
65
- const db = pg.options.database;
66
- log.debug(`cron.${name}`, 1, db);
67
- try {
68
- const data = await func({ pg, funcs, log });
69
- log.debug('cron', { db, name, result: data });
70
- log.info('cron', { db, name, result: data });
71
- }
72
- catch (err) {
73
- log.debug('cron', { db, name, error: err.toString() });
74
- log.error('cron', { db, name, error: err.toString() });
75
- }
76
- }
77
-
78
- /**
79
- * interval:
80
- * - 02:54 - every day
81
- * - 2:03 - every day
82
- * - *1:43 - 2 times a day
83
- * - *12:03 - 2 times a day
84
- * - **:54 - every hour
85
- * - **:*3 - every 10 minutes
86
- * - 60 - every minute
87
- * - 10 * 60 - every 10 minutes
88
- */
89
-
90
- export default async function addCron(func, interval, fastify) {
91
- if (!fastify) {
92
- throw new Error('not enough params: fastify');
93
- }
94
-
95
- const { config = {}, log } = fastify;
96
- const { time = {}, disabled = [] } = config.cron || {};
97
- const pg = getPG();
98
- const rclient = getRedis();
99
-
100
- const name = func.name || func.toString().split('/').at(-1).split('\'')[0];
101
-
102
- // if (!config.isServer) return;
103
-
104
- if (disabled.includes(name)) {
105
- log.debug('cron', { name, message: 'cron disabled' });
106
- return;
107
- }
108
-
109
- cronList[name] = func;
110
-
111
- const userInterval = time[name] || interval;
112
- const [waitMs, intervalMs] = interval2ms[typeof interval](userInterval);
113
-
114
- if (intervalMs < 1000) {
115
- log.warn('cron', { name, error: `interval ${interval} to small` });
116
- return;
117
- }
118
-
119
- // setTimeout to w8 for the time to start
120
- setTimeout(() => {
121
- runCron({
122
- pg, funcs: fastify, func, name, rclient, log,
123
- });
124
- // interval
125
- setInterval(() => {
126
- runCron({
127
- pg, funcs: fastify, func, name, rclient, log,
128
- });
129
- }, intervalMs);
130
- }, waitMs);
131
- }
1
+ import { createHash } from 'crypto';
2
+
3
+ import cronList from '../controllers/utils/cronList.js';
4
+ import getRedis from '../../redis/funcs/getRedis.js';
5
+ import getPG from '../../pg/funcs/getPG.js';
6
+
7
+ const md5 = (string) => createHash('md5').update(string).digest('hex');
8
+
9
+ async function verifyUnique(name, config, rclient) {
10
+ const cronId = config.port || 3000 + md5(name);
11
+ // one per node check
12
+ const key = `cron:unique:${cronId}`;
13
+ const unique = await rclient.setnx(key, 1);
14
+ const ttl = await rclient.ttl(key);
15
+ if (!unique && ttl !== -1) {
16
+ return false;
17
+ }
18
+ await rclient.expire(key, 20);
19
+ return true;
20
+ }
21
+
22
+ const intervalStringMs = {
23
+ everyMin: 1000 * 60,
24
+ tenMin: 1000 * 60 * 10,
25
+ everyHour: 1000 * 60 * 60,
26
+ isHalfday: 1000 * 60 * 60 * 12,
27
+ dailyHour: 1000 * 60 * 60 * 24,
28
+ };
29
+
30
+ const interval2ms = {
31
+ string: (interval) => {
32
+ const date = new Date();
33
+ const intervarSplit = interval.match(/^(\*{2}|(\*)?(\d{1,2})):(\*(\d)|(\d{2}))/);
34
+ if (!intervarSplit) {
35
+ throw new Error(`interval ${interval} not suported`);
36
+ }
37
+ const [, , isHalfday, dailyHour, , tenMin, HourlyMin] = intervarSplit;
38
+ const intervalMs = (isHalfday && intervalStringMs.isHalfday)
39
+ || (dailyHour && intervalStringMs.dailyHour)
40
+ || (tenMin && intervalStringMs.tenMin)
41
+ || intervalStringMs.everyHour;
42
+ const offsetDay = ((+dailyHour || 0) * 60 + (+tenMin || +HourlyMin)) * 60 * 1000;
43
+ const offsetCur = (date - date.getTimezoneOffset() * 1000 * 60) % intervalMs;
44
+ const waitMs = (offsetDay - offsetCur + intervalMs) % intervalMs;
45
+ return [waitMs, intervalMs];
46
+ },
47
+ number: (interval) => {
48
+ const date = new Date();
49
+ const intervalMs = interval * 1000;
50
+ const dateWithTZ = date - date.getTimezoneOffset() * 1000 * 60;
51
+ const offsetCur = dateWithTZ % intervalMs;
52
+ // start every cron within 1 hour
53
+ const sixtyMinutesStartMs = 3600000;
54
+ const waitMs = (intervalMs - offsetCur) % sixtyMinutesStartMs;
55
+ return [waitMs, intervalMs];
56
+ },
57
+ };
58
+
59
+ async function runCron({
60
+ pg, funcs, func, name, rclient, log,
61
+ }) {
62
+ const unique = await verifyUnique(name, funcs.config, rclient);
63
+
64
+ if (!unique) return;
65
+ const db = pg.options.database;
66
+ log.debug(`cron.${name}`, 1, db);
67
+ try {
68
+ const data = await func({ pg, funcs, log });
69
+ log.debug('cron', { db, name, result: data });
70
+ log.info('cron', { db, name, result: data });
71
+ }
72
+ catch (err) {
73
+ log.debug('cron', { db, name, error: err.toString() });
74
+ log.error('cron', { db, name, error: err.toString() });
75
+ }
76
+ }
77
+
78
+ /**
79
+ * interval:
80
+ * - 02:54 - every day
81
+ * - 2:03 - every day
82
+ * - *1:43 - 2 times a day
83
+ * - *12:03 - 2 times a day
84
+ * - **:54 - every hour
85
+ * - **:*3 - every 10 minutes
86
+ * - 60 - every minute
87
+ * - 10 * 60 - every 10 minutes
88
+ */
89
+
90
+ export default async function addCron(func, interval, fastify) {
91
+ if (!fastify) {
92
+ throw new Error('not enough params: fastify');
93
+ }
94
+
95
+ const { config = {}, log } = fastify;
96
+ const { time = {}, disabled = [] } = config.cron || {};
97
+ const pg = getPG();
98
+ const rclient = getRedis();
99
+
100
+ const name = func.name || func.toString().split('/').at(-1).split('\'')[0];
101
+
102
+ // if (!config.isServer) return;
103
+
104
+ if (disabled.includes(name)) {
105
+ log.debug('cron', { name, message: 'cron disabled' });
106
+ return;
107
+ }
108
+
109
+ cronList[name] = func;
110
+
111
+ const userInterval = time[name] || interval;
112
+ const [waitMs, intervalMs] = interval2ms[typeof interval](userInterval);
113
+
114
+ if (intervalMs < 1000) {
115
+ log.warn('cron', { name, error: `interval ${interval} to small` });
116
+ return;
117
+ }
118
+
119
+ // setTimeout to w8 for the time to start
120
+ setTimeout(() => {
121
+ runCron({
122
+ pg, funcs: fastify, func, name, rclient, log,
123
+ });
124
+ // interval
125
+ setInterval(() => {
126
+ runCron({
127
+ pg, funcs: fastify, func, name, rclient, log,
128
+ });
129
+ }, intervalMs);
130
+ }, waitMs);
131
+ }
package/cron/index.js CHANGED
@@ -1,10 +1,10 @@
1
- import cronApi from './controllers/cronApi.js';
2
- import addCron from './funcs/addCron.js';
3
-
4
- async function plugin(fastify, config = {}) {
5
- const prefix = config.prefix || '/api';
6
- fastify.decorate('addCron', addCron);
7
- fastify.get(`${prefix}/cron/:name`, {}, cronApi);
8
- }
9
-
10
- export default plugin;
1
+ import cronApi from './controllers/cronApi.js';
2
+ import addCron from './funcs/addCron.js';
3
+
4
+ async function plugin(fastify, config = {}) {
5
+ const prefix = config.prefix || '/api';
6
+ fastify.decorate('addCron', addCron);
7
+ fastify.get(`${prefix}/cron/:name`, {}, cronApi);
8
+ }
9
+
10
+ export default plugin;
@@ -1,14 +1,19 @@
1
- import dataDelete from '../funcs/dataDelete.js';
2
- import getTemplate from '../../table/controllers/utils/getTemplate.js';
3
-
4
- export default async function deleteCrud(req) {
5
- const loadTemplate = await getTemplate('table', req.opt?.table || req.params.table);
6
- const { table } = loadTemplate || req.opt || req.params || {};
7
- const { id } = req.opt || req.params || {};
8
-
9
- if (!table) return { status: 404, message: 'table is required' };
10
-
11
- const data = await dataDelete({ table, id });
12
-
13
- return { rowCount: data.rowCount, msg: !data.rowCount ? data : null };
14
- }
1
+ import dataDelete from '../funcs/dataDelete.js';
2
+ import getTemplate from '../../table/controllers/utils/getTemplate.js';
3
+ import getAccess from '../funcs/getAccess.js';
4
+
5
+ export default async function deleteCrud(req) {
6
+ const { actions = [], scope, my } = await getAccess(req, req.params.table, req.params.id) || {};
7
+ if (!actions.includes('del') || (scope === 'my' && !my)) {
8
+ return { message: 'access restricted', status: 403 };
9
+ }
10
+ const loadTemplate = await getTemplate('table', req.opt?.table || req.params.table);
11
+ const { table } = loadTemplate || req.opt || req.params || {};
12
+ const { id } = req.opt || req.params || {};
13
+
14
+ if (!table) return { status: 404, message: 'table is required' };
15
+
16
+ const data = await dataDelete({ table, id });
17
+
18
+ return { rowCount: data.rowCount, msg: !data.rowCount ? data : null };
19
+ }
@@ -1,48 +1,54 @@
1
- import dataInsert from '../funcs/dataInsert.js';
2
- import getToken from '../funcs/getToken.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
- if (!req.params?.table) {
8
- return { message: 'table is required', status: 400 };
9
- }
10
- const loadTemplate = await getTemplate('table', req.params.table);
11
- const { table, public: ispublic } = loadTemplate || req.params || {};
12
- if (!table) {
13
- return { message: 'table not found', status: 404 };
14
- }
15
-
16
- const { funcs = {}, user = {}, params = {} } = req;
17
- const uid = funcs.config?.auth?.disable || ispublic ? '1' : user.uid;
18
- const tokenDataString = await getToken({
19
- funcs, uid, token: params.table, mode: 'a', json: 0,
20
- });
21
-
22
- const { form, add } = JSON.parse(tokenDataString || '{}');
23
-
24
- const formData = form || loadTemplate?.form ? (await getTemplate('form', form || loadTemplate?.form) || {}) : {};
25
-
26
- const xssCheck = checkXSS({ body: req.body, schema: formData?.schema });
27
-
28
- if (xssCheck.error && formData?.xssCheck !== false) {
29
- req.log.warn({ name: 'injection/xss', msg: xssCheck.error, table }, req);
30
- return { message: 'Дані містять заборонені символи. Приберіть їх та спробуйте ще раз', status: 409 };
31
- }
32
-
33
- const res = await dataInsert({ table: add || table, data: req.body });
34
-
35
- const extraKeys = Object.keys(formData)?.filter((key) => formData?.[key]?.type === 'DataTable' && formData?.[key]?.table && formData?.[key]?.parent_id && req.body[key].length);
36
- if (extraKeys?.length) {
37
- res.extra = {};
38
- await Promise.all(extraKeys?.map(async (key) => {
39
- const extraRows = await Promise.all(req.body[key].map(async (row) => {
40
- const extraRes = await dataInsert({ table: formData[key].table, data: { ...row, [formData[key].parent_id]: req.body[formData[key].parent_id] } });
41
- return extraRes?.rows?.[0];
42
- }));
43
- Object.assign(res.extra, { [key]: extraRows.filter((el) => el) });
44
- }));
45
- }
46
-
47
- return { rows: res.rows, extra: res.extra };
48
- }
1
+ import dataInsert from '../funcs/dataInsert.js';
2
+ import getToken from '../funcs/getToken.js';
3
+ import checkXSS from './utils/checkXSS.js';
4
+ import getTemplate from '../../table/controllers/utils/getTemplate.js';
5
+ import getAccess from '../funcs/getAccess.js';
6
+
7
+ export default async function insert(req) {
8
+ const { actions = [] } = await getAccess(req, req.params.table) || {};
9
+ if (!actions.includes('edit')) {
10
+ return { message: 'access restricted', status: 403 };
11
+ }
12
+ if (!req.params?.table) {
13
+ return { message: 'table is required', status: 400 };
14
+ }
15
+ const loadTemplate = await getTemplate('table', req.params.table);
16
+ const { table, public: ispublic } = loadTemplate || req.params || {};
17
+ if (!table) {
18
+ return { message: 'table not found', status: 404 };
19
+ }
20
+
21
+ const { funcs = {}, user = {}, params = {} } = req;
22
+ const tokenDataString = await getToken({
23
+ funcs, uid: user.uid, token: params.table, mode: 'a', json: 0,
24
+ });
25
+
26
+ const { form, add } = JSON.parse(tokenDataString || '{}');
27
+
28
+ const formData = form || loadTemplate?.form ? (await getTemplate('form', form || loadTemplate?.form) || {}) : {};
29
+
30
+ const xssCheck = checkXSS({ body: req.body, schema: formData?.schema });
31
+
32
+ if (xssCheck.error && formData?.xssCheck !== false) {
33
+ req.log.warn({ name: 'injection/xss', msg: xssCheck.error, table }, req);
34
+ return { message: 'Дані містять заборонені символи. Приберіть їх та спробуйте ще раз', status: 409 };
35
+ }
36
+
37
+ const { uid } = funcs.config?.auth?.disable || ispublic ? { uid: '1' } : user || {};
38
+ Object.assign(req.body, { uid, editor_id: uid });
39
+ const res = await dataInsert({ table: add || table, data: req.body });
40
+
41
+ const extraKeys = Object.keys(formData)?.filter((key) => formData?.[key]?.type === 'DataTable' && formData?.[key]?.table && formData?.[key]?.parent_id && req.body[key].length);
42
+ if (extraKeys?.length) {
43
+ res.extra = {};
44
+ await Promise.all(extraKeys?.map(async (key) => {
45
+ const extraRows = await Promise.all(req.body[key].map(async (row) => {
46
+ const extraRes = await dataInsert({ table: formData[key].table, data: { ...row, [formData[key].parent_id]: req.body[formData[key].parent_id] } });
47
+ return extraRes?.rows?.[0];
48
+ }));
49
+ Object.assign(res.extra, { [key]: extraRows.filter((el) => el) });
50
+ }));
51
+ }
52
+
53
+ return { rows: res.rows, extra: res.extra };
54
+ }
@@ -1,54 +1,59 @@
1
- import dataUpdate from '../funcs/dataUpdate.js';
2
- import dataInsert from '../funcs/dataInsert.js';
3
- import pgClients from '../../pg/pgClients.js';
4
- import getToken from '../funcs/getToken.js';
5
- import checkXSS from './utils/checkXSS.js';
6
- import getTemplate from '../../table/controllers/utils/getTemplate.js';
7
-
8
- export default async function update(req) {
9
- if (!req.params?.table) {
10
- return { message: 'table is required', status: 400 };
11
- }
12
- if (!req.params?.id) {
13
- return { message: 'id is required', status: 404 };
14
- }
15
- const loadTemplate = await getTemplate('table', req.params.table);
16
- const { table, public: ispublic } = loadTemplate || req.params || {};
17
- const { id } = req.params || {};
18
-
19
- const { funcs = {}, user = {}, params = {} } = req;
20
- const uid = funcs.config?.auth?.disable || ispublic ? '1' : user.uid;
21
- const tokenDataString = await getToken({
22
- funcs, uid, token: params.table, mode: 'w', json: 0,
23
- });
24
-
25
- const tokenData = JSON.parse(tokenDataString || '{}');
26
-
27
- const formData = tokenData?.form || loadTemplate?.form ? await getTemplate('form', tokenData.form || loadTemplate?.form) : {};
28
-
29
- const xssCheck = checkXSS({ body: req.body, schema: formData?.schema });
30
-
31
- if (xssCheck.error && formData?.xssCheck !== false) {
32
- req.log.warn({ name: 'injection/xss', msg: xssCheck.error, table }, req);
33
- return { message: 'Дані містять заборонені символи. Приберіть їх та спробуйте ще раз', status: 409 };
34
- }
35
-
36
- const res = await dataUpdate({ table: tokenData?.table || table, id: tokenData?.id || id, data: req.body });
37
-
38
- const extraKeys = Object.keys(formData)?.filter((key) => formData?.[key]?.type === 'DataTable' && formData?.[key]?.table && formData?.[key]?.parent_id && req.body[key].length);
39
- if (extraKeys?.length) {
40
- res.extra = {};
41
- await Promise.all(extraKeys?.map(async (key) => {
42
- // delete old extra data
43
- await pgClients.client.query(`delete from ${formData[key].table} where ${formData[key].parent_id}=$1`, [req.body[formData[key].parent_id]]);
44
- // insert new extra data
45
- const extraRows = await Promise.all(req.body[key].map(async (row) => {
46
- const extraRes = await dataInsert({ table: formData[key].table, data: { ...row, [formData[key].parent_id]: req.body[formData[key].parent_id] } });
47
- return extraRes?.rows?.[0];
48
- }));
49
- Object.assign(res.extra, { [key]: extraRows.filter((el) => el) });
50
- }));
51
- }
52
-
53
- return res;
54
- }
1
+ import dataUpdate from '../funcs/dataUpdate.js';
2
+ import dataInsert from '../funcs/dataInsert.js';
3
+ import pgClients from '../../pg/pgClients.js';
4
+ import getToken from '../funcs/getToken.js';
5
+ import checkXSS from './utils/checkXSS.js';
6
+ import getTemplate from '../../table/controllers/utils/getTemplate.js';
7
+ import getAccess from '../funcs/getAccess.js';
8
+
9
+ export default async function update(req) {
10
+ const { actions = [], scope, my } = await getAccess(req, req.params.table, req.params.id) || {};
11
+ if (!actions.includes('edit') || (scope === 'my' && !my)) {
12
+ return { message: 'access restricted', status: 403 };
13
+ }
14
+ if (!req.params?.table) {
15
+ return { message: 'table is required', status: 400 };
16
+ }
17
+ if (!req.params?.id) {
18
+ return { message: 'id is required', status: 404 };
19
+ }
20
+ const loadTemplate = await getTemplate('table', req.params.table);
21
+ const { table, public: ispublic } = loadTemplate || req.params || {};
22
+ const { id } = req.params || {};
23
+
24
+ const { funcs = {}, user = {}, params = {} } = req;
25
+ const uid = funcs.config?.auth?.disable || ispublic ? '1' : user.uid;
26
+ const tokenDataString = await getToken({
27
+ funcs, uid, token: params.table, mode: 'w', json: 0,
28
+ });
29
+
30
+ const tokenData = JSON.parse(tokenDataString || '{}');
31
+
32
+ const formData = tokenData?.form || loadTemplate?.form ? await getTemplate('form', tokenData.form || loadTemplate?.form) : {};
33
+
34
+ const xssCheck = checkXSS({ body: req.body, schema: formData?.schema });
35
+
36
+ if (xssCheck.error && formData?.xssCheck !== false) {
37
+ req.log.warn({ name: 'injection/xss', msg: xssCheck.error, table }, req);
38
+ return { message: 'Дані містять заборонені символи. Приберіть їх та спробуйте ще раз', status: 409 };
39
+ }
40
+
41
+ const res = await dataUpdate({ table: tokenData?.table || table, id: tokenData?.id || id, data: req.body });
42
+
43
+ const extraKeys = Object.keys(formData)?.filter((key) => formData?.[key]?.type === 'DataTable' && formData?.[key]?.table && formData?.[key]?.parent_id && req.body[key].length);
44
+ if (extraKeys?.length) {
45
+ res.extra = {};
46
+ await Promise.all(extraKeys?.map(async (key) => {
47
+ // delete old extra data
48
+ await pgClients.client.query(`delete from ${formData[key].table} where ${formData[key].parent_id}=$1`, [req.body[formData[key].parent_id]]);
49
+ // insert new extra data
50
+ const extraRows = await Promise.all(req.body[key].map(async (row) => {
51
+ const extraRes = await dataInsert({ table: formData[key].table, data: { ...row, [formData[key].parent_id]: req.body[formData[key].parent_id] } });
52
+ return extraRes?.rows?.[0];
53
+ }));
54
+ Object.assign(res.extra, { [key]: extraRows.filter((el) => el) });
55
+ }));
56
+ }
57
+
58
+ return res;
59
+ }
@@ -1,45 +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;
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;