dbgate-api-premium 6.5.4 → 6.5.6

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.
@@ -16,7 +16,7 @@ const connections = require('../controllers/connections');
16
16
  const { getAuthProviderFromReq } = require('../auth/authProvider');
17
17
  const { checkLicense, checkLicenseKey } = require('../utility/checkLicense');
18
18
  const storage = require('./storage');
19
- const { getAuthProxyUrl } = require('../utility/authProxy');
19
+ const { getAuthProxyUrl, tryToGetRefreshedLicense } = require('../utility/authProxy');
20
20
  const { getPublicHardwareFingerprint } = require('../utility/hardwareFingerprint');
21
21
  const { extractErrorMessage } = require('dbgate-tools');
22
22
  const {
@@ -29,6 +29,7 @@ const {
29
29
  } = require('../utility/crypting');
30
30
 
31
31
  const lock = new AsyncLock();
32
+ let cachedSettingsValue = null;
32
33
 
33
34
  module.exports = {
34
35
  // settingsValue: {},
@@ -108,6 +109,7 @@ module.exports = {
108
109
  ),
109
110
  isAdminPasswordMissing,
110
111
  isInvalidToken: req?.isInvalidToken,
112
+ skipAllAuth: !!process.env.SKIP_ALL_AUTH,
111
113
  adminPasswordState: adminConfig?.adminPasswordState,
112
114
  storageDatabase: process.env.STORAGE_DATABASE,
113
115
  logsFilePath: getLogsFilePath(),
@@ -118,6 +120,7 @@ module.exports = {
118
120
  supportCloudAutoUpgrade: !!process.env.CLOUD_UPGRADE_FILE,
119
121
  allowPrivateCloud: platformInfo.isElectron || !!process.env.ALLOW_DBGATE_PRIVATE_CLOUD,
120
122
  ...currentVersion,
123
+ redirectToDbGateCloudLogin: !!process.env.REDIRECT_TO_DBGATE_CLOUD_LOGIN,
121
124
  };
122
125
 
123
126
  return configResult;
@@ -144,6 +147,13 @@ module.exports = {
144
147
  return res;
145
148
  },
146
149
 
150
+ async getCachedSettings() {
151
+ if (!cachedSettingsValue) {
152
+ cachedSettingsValue = await this.loadSettings();
153
+ }
154
+ return cachedSettingsValue;
155
+ },
156
+
147
157
  deleteSettings_meta: true,
148
158
  async deleteSettings() {
149
159
  await fs.unlink(path.join(datadir(), processArgs.runE2eTests ? 'settings-e2etests.json' : 'settings.json'));
@@ -182,6 +192,7 @@ module.exports = {
182
192
  return {
183
193
  ...this.fillMissingSettings(JSON.parse(settingsText)),
184
194
  'other.licenseKey': platformInfo.isElectron ? await this.loadLicenseKey() : undefined,
195
+ // 'other.licenseKey': await this.loadLicenseKey(),
185
196
  };
186
197
  }
187
198
  } catch (err) {
@@ -199,21 +210,34 @@ module.exports = {
199
210
  },
200
211
 
201
212
  saveLicenseKey_meta: true,
202
- async saveLicenseKey({ licenseKey }) {
203
- const decoded = jwt.decode(licenseKey?.trim());
204
- if (!decoded) {
205
- return {
206
- status: 'error',
207
- errorMessage: 'Invalid license key',
208
- };
209
- }
213
+ async saveLicenseKey({ licenseKey, forceSave = false, tryToRenew = false }) {
214
+ if (!forceSave) {
215
+ const decoded = jwt.decode(licenseKey?.trim());
216
+ if (!decoded) {
217
+ return {
218
+ status: 'error',
219
+ errorMessage: 'Invalid license key',
220
+ };
221
+ }
210
222
 
211
- const { exp } = decoded;
212
- if (exp * 1000 < Date.now()) {
213
- return {
214
- status: 'error',
215
- errorMessage: 'License key is expired',
216
- };
223
+ const { exp } = decoded;
224
+ if (exp * 1000 < Date.now()) {
225
+ let renewed = false;
226
+ if (tryToRenew) {
227
+ const newLicenseKey = await tryToGetRefreshedLicense(licenseKey);
228
+ if (newLicenseKey.status == 'ok') {
229
+ licenseKey = newLicenseKey.token;
230
+ renewed = true;
231
+ }
232
+ }
233
+
234
+ if (!renewed) {
235
+ return {
236
+ status: 'error',
237
+ errorMessage: 'License key is expired',
238
+ };
239
+ }
240
+ }
217
241
  }
218
242
 
219
243
  try {
@@ -257,6 +281,7 @@ module.exports = {
257
281
  updateSettings_meta: true,
258
282
  async updateSettings(values, req) {
259
283
  if (!hasPermission(`settings/change`, req)) return false;
284
+ cachedSettingsValue = null;
260
285
 
261
286
  const res = await lock.acquire('settings', async () => {
262
287
  const currentValue = await this.loadSettings();
@@ -265,7 +290,11 @@ module.exports = {
265
290
  if (process.env.STORAGE_DATABASE) {
266
291
  updated = {
267
292
  ...currentValue,
268
- ...values,
293
+ ..._.mapValues(values, v => {
294
+ if (v === true) return 'true';
295
+ if (v === false) return 'false';
296
+ return v;
297
+ }),
269
298
  };
270
299
  await storage.writeConfig({
271
300
  group: 'settings',
@@ -283,7 +312,7 @@ module.exports = {
283
312
  // this.settingsValue = updated;
284
313
 
285
314
  if (currentValue['other.licenseKey'] != values['other.licenseKey']) {
286
- await this.saveLicenseKey({ licenseKey: values['other.licenseKey'] });
315
+ await this.saveLicenseKey({ licenseKey: values['other.licenseKey'], forceSave: true });
287
316
  socket.emitChanged(`config-changed`);
288
317
  }
289
318
  }
@@ -303,7 +332,7 @@ module.exports = {
303
332
  const resp = await axios.default.get('https://raw.githubusercontent.com/dbgate/dbgate/master/CHANGELOG.md');
304
333
  return resp.data;
305
334
  } catch (err) {
306
- return ''
335
+ return '';
307
336
  }
308
337
  },
309
338
 
@@ -313,6 +342,16 @@ module.exports = {
313
342
  return resp;
314
343
  },
315
344
 
345
+ getNewLicense_meta: true,
346
+ async getNewLicense({ oldLicenseKey }) {
347
+ const newLicenseKey = await tryToGetRefreshedLicense(oldLicenseKey);
348
+ const res = await checkLicenseKey(newLicenseKey.token);
349
+ if (res.status == 'ok') {
350
+ res.licenseKey = newLicenseKey.token;
351
+ }
352
+ return res;
353
+ },
354
+
316
355
  recryptDatabaseForExport(db) {
317
356
  const encryptionKey = generateTransportEncryptionKey();
318
357
  const transportEncryptor = createTransportEncryptor(encryptionKey);
@@ -536,14 +536,14 @@ module.exports = {
536
536
  },
537
537
 
538
538
  dbloginAuthToken_meta: true,
539
- async dbloginAuthToken({ amoid, code, conid, redirectUri, sid }) {
539
+ async dbloginAuthToken({ amoid, code, conid, redirectUri, sid }, req) {
540
540
  try {
541
541
  const connection = await this.getCore({ conid });
542
542
  const driver = requireEngineDriver(connection);
543
543
  const accessToken = await driver.getAuthTokenFromCode(connection, { code, redirectUri, sid });
544
544
  const volatile = await this.saveVolatile({ conid, accessToken });
545
545
  const authProvider = getAuthProviderById(amoid);
546
- const resp = await authProvider.login(null, null, { conid: volatile._id });
546
+ const resp = await authProvider.login(null, null, { conid: volatile._id }, req);
547
547
  return resp;
548
548
  } catch (err) {
549
549
  logger.error(extractErrorLogData(err), 'Error getting DB token');
@@ -552,18 +552,18 @@ module.exports = {
552
552
  },
553
553
 
554
554
  dbloginAuth_meta: true,
555
- async dbloginAuth({ amoid, conid, user, password }) {
555
+ async dbloginAuth({ amoid, conid, user, password }, req) {
556
556
  if (user || password) {
557
557
  const saveResp = await this.saveVolatile({ conid, user, password, test: true });
558
558
  if (saveResp.msgtype == 'connected') {
559
- const loginResp = await getAuthProviderById(amoid).login(user, password, { conid: saveResp._id });
559
+ const loginResp = await getAuthProviderById(amoid).login(user, password, { conid: saveResp._id }, req);
560
560
  return loginResp;
561
561
  }
562
562
  return saveResp;
563
563
  }
564
564
 
565
565
  // user and password is stored in connection, volatile connection is not needed
566
- const loginResp = await getAuthProviderById(amoid).login(null, null, { conid });
566
+ const loginResp = await getAuthProviderById(amoid).login(null, null, { conid }, req);
567
567
  return loginResp;
568
568
  },
569
569
 
@@ -41,6 +41,7 @@ const { decryptConnection } = require('../utility/crypting');
41
41
  const { getSshTunnel } = require('../utility/sshTunnel');
42
42
  const sessions = require('./sessions');
43
43
  const jsldata = require('./jsldata');
44
+ const { sendToAuditLog } = require('../utility/auditlog');
44
45
 
45
46
  const logger = getLogger('databaseConnections');
46
47
 
@@ -83,8 +84,11 @@ module.exports = {
83
84
  }
84
85
  },
85
86
  handle_response(conid, database, { msgid, ...response }) {
86
- const [resolve, reject] = this.requests[msgid];
87
+ const [resolve, reject, additionalData] = this.requests[msgid];
87
88
  resolve(response);
89
+ if (additionalData?.auditLogger) {
90
+ additionalData?.auditLogger(response);
91
+ }
88
92
  delete this.requests[msgid];
89
93
  },
90
94
  handle_status(conid, database, { status }) {
@@ -215,10 +219,10 @@ module.exports = {
215
219
  },
216
220
 
217
221
  /** @param {import('dbgate-types').OpenedDatabaseConnection} conn */
218
- sendRequest(conn, message) {
222
+ sendRequest(conn, message, additionalData = {}) {
219
223
  const msgid = crypto.randomUUID();
220
224
  const promise = new Promise((resolve, reject) => {
221
- this.requests[msgid] = [resolve, reject];
225
+ this.requests[msgid] = [resolve, reject, additionalData];
222
226
  try {
223
227
  conn.subprocess.send({ msgid, ...message });
224
228
  } catch (err) {
@@ -242,18 +246,57 @@ module.exports = {
242
246
  },
243
247
 
244
248
  sqlSelect_meta: true,
245
- async sqlSelect({ conid, database, select }, req) {
249
+ async sqlSelect({ conid, database, select, auditLogSessionGroup }, req) {
246
250
  testConnectionPermission(conid, req);
247
251
  const opened = await this.ensureOpened(conid, database);
248
- const res = await this.sendRequest(opened, { msgtype: 'sqlSelect', select });
252
+ const res = await this.sendRequest(
253
+ opened,
254
+ { msgtype: 'sqlSelect', select },
255
+ {
256
+ auditLogger:
257
+ auditLogSessionGroup && select?.from?.name?.pureName
258
+ ? response => {
259
+ sendToAuditLog(req, {
260
+ category: 'dbop',
261
+ component: 'DatabaseConnectionsController',
262
+ event: 'sql.select',
263
+ action: 'select',
264
+ severity: 'info',
265
+ conid,
266
+ database,
267
+ schemaName: select?.from?.name?.schemaName,
268
+ pureName: select?.from?.name?.pureName,
269
+ sumint1: response?.rows?.length,
270
+ sessionParam: `${conid}::${database}::${select?.from?.name?.schemaName || '0'}::${
271
+ select?.from?.name?.pureName
272
+ }`,
273
+ sessionGroup: auditLogSessionGroup,
274
+ message: `Loaded table data from ${select?.from?.name?.pureName}`,
275
+ });
276
+ }
277
+ : null,
278
+ }
279
+ );
249
280
  return res;
250
281
  },
251
282
 
252
283
  runScript_meta: true,
253
- async runScript({ conid, database, sql, useTransaction }, req) {
284
+ async runScript({ conid, database, sql, useTransaction, logMessage }, req) {
254
285
  testConnectionPermission(conid, req);
255
286
  logger.info({ conid, database, sql }, 'Processing script');
256
287
  const opened = await this.ensureOpened(conid, database);
288
+ sendToAuditLog(req, {
289
+ category: 'dbop',
290
+ component: 'DatabaseConnectionsController',
291
+ event: 'sql.runscript',
292
+ action: 'runscript',
293
+ severity: 'info',
294
+ conid,
295
+ database,
296
+ detail: sql,
297
+ message: logMessage || `Running SQL script`,
298
+ });
299
+
257
300
  const res = await this.sendRequest(opened, { msgtype: 'runScript', sql, useTransaction });
258
301
  return res;
259
302
  },
@@ -262,16 +305,53 @@ module.exports = {
262
305
  async runOperation({ conid, database, operation, useTransaction }, req) {
263
306
  testConnectionPermission(conid, req);
264
307
  logger.info({ conid, database, operation }, 'Processing operation');
308
+
309
+ sendToAuditLog(req, {
310
+ category: 'dbop',
311
+ component: 'DatabaseConnectionsController',
312
+ event: 'sql.runoperation',
313
+ action: operation.type,
314
+ severity: 'info',
315
+ conid,
316
+ database,
317
+ detail: operation,
318
+ message: `Running DB operation: ${operation.type}`,
319
+ });
320
+
265
321
  const opened = await this.ensureOpened(conid, database);
266
322
  const res = await this.sendRequest(opened, { msgtype: 'runOperation', operation, useTransaction });
267
323
  return res;
268
324
  },
269
325
 
270
326
  collectionData_meta: true,
271
- async collectionData({ conid, database, options }, req) {
327
+ async collectionData({ conid, database, options, auditLogSessionGroup }, req) {
272
328
  testConnectionPermission(conid, req);
273
329
  const opened = await this.ensureOpened(conid, database);
274
- const res = await this.sendRequest(opened, { msgtype: 'collectionData', options });
330
+ const res = await this.sendRequest(
331
+ opened,
332
+ { msgtype: 'collectionData', options },
333
+ {
334
+ auditLogger:
335
+ auditLogSessionGroup && options?.pureName
336
+ ? response => {
337
+ sendToAuditLog(req, {
338
+ category: 'dbop',
339
+ component: 'DatabaseConnectionsController',
340
+ event: 'nosql.collectionData',
341
+ action: 'select',
342
+ severity: 'info',
343
+ conid,
344
+ database,
345
+ pureName: options?.pureName,
346
+ sumint1: response?.result?.rows?.length,
347
+ sessionParam: `${conid}::${database}::${options?.pureName}`,
348
+ sessionGroup: auditLogSessionGroup,
349
+ message: `Loaded collection data ${options?.pureName}`,
350
+ });
351
+ }
352
+ : null,
353
+ }
354
+ );
275
355
  return res.result || null;
276
356
  },
277
357
 
@@ -492,6 +572,20 @@ module.exports = {
492
572
  }
493
573
 
494
574
  const opened = await this.ensureOpened(conid, database);
575
+
576
+ sendToAuditLog(req, {
577
+ category: 'dbop',
578
+ component: 'DatabaseConnectionsController',
579
+ action: 'structure',
580
+ event: 'dbStructure.get',
581
+ severity: 'info',
582
+ conid,
583
+ database,
584
+ sessionParam: `${conid}::${database}`,
585
+ sessionGroup: 'getStructure',
586
+ message: `Loaded database structure for ${database}`,
587
+ });
588
+
495
589
  return opened.structure;
496
590
  // const existing = this.opened.find((x) => x.conid == conid && x.database == database);
497
591
  // if (existing) return existing.status;
@@ -203,10 +203,10 @@ module.exports = {
203
203
  },
204
204
 
205
205
  exportChart_meta: true,
206
- async exportChart({ filePath, title, config, image }) {
206
+ async exportChart({ filePath, title, config, image, plugins }) {
207
207
  const fileName = path.parse(filePath).base;
208
208
  const imageFile = fileName.replace('.html', '-preview.png');
209
- const html = getChartExport(title, config, imageFile);
209
+ const html = getChartExport(title, config, imageFile, plugins);
210
210
  await fs.writeFile(filePath, html);
211
211
  if (image) {
212
212
  const index = image.indexOf('base64,');
@@ -20,6 +20,7 @@ const { handleProcessCommunication } = require('../utility/processComm');
20
20
  const processArgs = require('../utility/processArgs');
21
21
  const platformInfo = require('../utility/platformInfo');
22
22
  const { checkSecureDirectories, checkSecureDirectoriesInScript } = require('../utility/security');
23
+ const { sendToAuditLog, logJsonRunnerScript } = require('../utility/auditlog');
23
24
  const logger = getLogger('runners');
24
25
 
25
26
  function extractPlugins(script) {
@@ -270,7 +271,7 @@ module.exports = {
270
271
  },
271
272
 
272
273
  start_meta: true,
273
- async start({ script }) {
274
+ async start({ script }, req) {
274
275
  const runid = crypto.randomUUID();
275
276
 
276
277
  if (script.type == 'json') {
@@ -280,14 +281,36 @@ module.exports = {
280
281
  }
281
282
  }
282
283
 
284
+ logJsonRunnerScript(req, script);
285
+
283
286
  const js = await jsonScriptToJavascript(script);
284
287
  return this.startCore(runid, scriptTemplate(js, false));
285
288
  }
286
289
 
287
290
  if (!platformInfo.allowShellScripting) {
291
+ sendToAuditLog(req, {
292
+ category: 'shell',
293
+ component: 'RunnersController',
294
+ event: 'script.runFailed',
295
+ action: 'script',
296
+ severity: 'warn',
297
+ detail: script,
298
+ message: 'Scripts are not allowed',
299
+ });
300
+
288
301
  return { errorMessage: 'Shell scripting is not allowed' };
289
302
  }
290
303
 
304
+ sendToAuditLog(req, {
305
+ category: 'shell',
306
+ component: 'RunnersController',
307
+ event: 'script.run.shell',
308
+ action: 'script',
309
+ severity: 'info',
310
+ detail: script,
311
+ message: 'Running JS script',
312
+ });
313
+
291
314
  return this.startCore(runid, scriptTemplate(script, false));
292
315
  },
293
316
 
@@ -12,6 +12,7 @@ const { testConnectionPermission } = require('../utility/hasPermission');
12
12
  const { MissingCredentialsError } = require('../utility/exceptions');
13
13
  const pipeForkLogs = require('../utility/pipeForkLogs');
14
14
  const { getLogger, extractErrorLogData } = require('dbgate-tools');
15
+ const { sendToAuditLog } = require('../utility/auditlog');
15
16
 
16
17
  const logger = getLogger('serverConnection');
17
18
 
@@ -145,6 +146,17 @@ module.exports = {
145
146
  if (conid == '__model') return [];
146
147
  testConnectionPermission(conid, req);
147
148
  const opened = await this.ensureOpened(conid);
149
+ sendToAuditLog(req, {
150
+ category: 'serverop',
151
+ component: 'ServerConnectionsController',
152
+ action: 'listDatabases',
153
+ event: 'databases.list',
154
+ severity: 'info',
155
+ conid,
156
+ sessionParam: `${conid}`,
157
+ sessionGroup: 'listDatabases',
158
+ message: `Loaded databases for connection`,
159
+ });
148
160
  return opened?.databases ?? [];
149
161
  },
150
162
 
@@ -11,6 +11,7 @@ const { appdir } = require('../utility/directories');
11
11
  const { getLogger, extractErrorLogData } = require('dbgate-tools');
12
12
  const pipeForkLogs = require('../utility/pipeForkLogs');
13
13
  const config = require('./config');
14
+ const { sendToAuditLog } = require('../utility/auditlog');
14
15
 
15
16
  const logger = getLogger('sessions');
16
17
 
@@ -146,12 +147,24 @@ module.exports = {
146
147
  },
147
148
 
148
149
  executeQuery_meta: true,
149
- async executeQuery({ sesid, sql, autoCommit, autoDetectCharts, limitRows, frontMatter }) {
150
+ async executeQuery({ sesid, sql, autoCommit, autoDetectCharts, limitRows, frontMatter }, req) {
150
151
  const session = this.opened.find(x => x.sesid == sesid);
151
152
  if (!session) {
152
153
  throw new Error('Invalid session');
153
154
  }
154
155
 
156
+ sendToAuditLog(req, {
157
+ category: 'dbop',
158
+ component: 'SessionController',
159
+ action: 'executeQuery',
160
+ event: 'query.execute',
161
+ severity: 'info',
162
+ detail: sql,
163
+ conid: session.conid,
164
+ database: session.database,
165
+ message: 'Executing query',
166
+ });
167
+
155
168
  logger.info({ sesid, sql }, 'Processing query');
156
169
  this.dispatchMessage(sesid, 'Query execution started');
157
170
  session.subprocess.send({
@@ -18,13 +18,14 @@ const {
18
18
  const { hasPermission } = require('../utility/hasPermission');
19
19
  const { changeSetToSql, removeSchemaFromChangeSet } = require('dbgate-datalib');
20
20
  const storageModel = require('../storageModel');
21
- const { dumpSqlCommand } = require('dbgate-sqltree');
21
+ const { dumpSqlCommand, dumpSqlSelect } = require('dbgate-sqltree');
22
22
  const {
23
23
  runCommandOnDriver,
24
24
  getLogger,
25
25
  runQueryFmt,
26
26
  getPredefinedPermissions,
27
27
  runQueryOnDriver,
28
+ safeJsonParse,
28
29
  } = require('dbgate-tools');
29
30
  const socket = require('../utility/socket');
30
31
  const { obtainRefreshedLicense } = require('../utility/authProxy');
@@ -38,6 +39,7 @@ const {
38
39
  const crypto = require('crypto');
39
40
  const dataReplicator = require('../shell/dataReplicator');
40
41
  const storageReplicatorItems = require('../utility/storageReplicatorItems');
42
+ const { sendToAuditLog } = require('../utility/auditlog');
41
43
 
42
44
  const logger = getLogger('storage');
43
45
 
@@ -226,9 +228,9 @@ module.exports = {
226
228
  conn,
227
229
  'update ~auth_methods set ~name=%v, ~is_disabled=%v, ~is_default = %v, ~is_collapsed = %v where ~id = %v',
228
230
  method.name,
229
- method.isDisabled,
230
- method.isDefault,
231
- method.isCollapsed,
231
+ method.isDisabled ? 1 : 0,
232
+ method.isDefault ? 1 : 0,
233
+ method.isCollapsed ? 1 : 0,
232
234
  method.id
233
235
  );
234
236
  } else {
@@ -618,6 +620,30 @@ module.exports = {
618
620
  return true;
619
621
  },
620
622
 
623
+ copyConnection_meta: true,
624
+ async copyConnection({ id, name }) {
625
+ const [conn, driver] = await getStorageConnection();
626
+ if (!conn) {
627
+ return null;
628
+ }
629
+
630
+ const oldConnection = await storageSelectFmt(`select * from ~connections where ~id = %v`, id);
631
+ const oldConnectionPairs = Object.entries(oldConnection[0] || {})
632
+ .filter(x => x[0] != 'id')
633
+ .map(x => (x[0] == 'displayName' ? [x[0], name] : [x[0], x[1]]))
634
+ .map(x => (x[0] == 'conid' ? [x[0], crypto.randomUUID()] : [x[0], x[1]]));
635
+ await runQueryFmt(
636
+ driver,
637
+ conn,
638
+ 'insert into ~connections (%,i) values (%,v)',
639
+ oldConnectionPairs.map(x => x[0]),
640
+ oldConnectionPairs.map(x => x[1])
641
+ );
642
+ socket.emitChanged('connection-list-changed');
643
+
644
+ return true;
645
+ },
646
+
621
647
  getRoleList_meta: true,
622
648
  async getRoleList() {
623
649
  const resp = await storageSelectFmt(`select ~roles.~id,~roles.~name from ~roles`);
@@ -699,6 +725,103 @@ module.exports = {
699
725
  return true;
700
726
  },
701
727
 
728
+ getAuditLog_meta: true,
729
+ async getAuditLog({ offset = 0, limit = 100, dateFrom = 0, dateTo = new Date().getTime(), filters = {} }) {
730
+ const [conn, driver] = await getStorageConnection();
731
+ const conditions = [
732
+ {
733
+ conditionType: 'binary',
734
+ operator: '>=',
735
+ left: { exprType: 'column', columnName: 'created' },
736
+ right: { exprType: 'value', value: dateFrom },
737
+ },
738
+ {
739
+ conditionType: 'binary',
740
+ operator: '<=',
741
+ left: { exprType: 'column', columnName: 'created' },
742
+ right: { exprType: 'value', value: dateTo },
743
+ },
744
+ ];
745
+ for (const [key, values] of Object.entries(filters)) {
746
+ if (values.length == 1 && values[0] == null) {
747
+ // @ts-ignore
748
+ conditions.push({
749
+ conditionType: 'isNull',
750
+ expr: { exprType: 'column', columnName: key },
751
+ });
752
+ continue;
753
+ }
754
+ // @ts-ignore
755
+ conditions.push({
756
+ conditionType: 'in',
757
+ expr: { exprType: 'column', columnName: key },
758
+ values,
759
+ });
760
+ }
761
+ const COLUMNS = [
762
+ 'id',
763
+ 'created',
764
+ 'user_login',
765
+ 'event',
766
+ 'conid',
767
+ 'database',
768
+ 'connection_data',
769
+ 'pure_name',
770
+ 'message',
771
+ ];
772
+ const select = {
773
+ commandType: 'select',
774
+ from: {
775
+ name: {
776
+ pureName: 'audit_log',
777
+ },
778
+ },
779
+ columns: COLUMNS.map(columnName => ({
780
+ exprType: 'column',
781
+ columnName,
782
+ })),
783
+ where: {
784
+ conditionType: 'and',
785
+ conditions,
786
+ },
787
+ range: {
788
+ limit: limit,
789
+ offset: offset,
790
+ },
791
+ orderBy: [
792
+ {
793
+ exprType: 'column',
794
+ columnName: 'id',
795
+ direction: 'desc',
796
+ },
797
+ ],
798
+ };
799
+ const dmp = driver.createDumper();
800
+ // @ts-ignore
801
+ dumpSqlSelect(dmp, select);
802
+ const resp = await driver.query(conn, dmp.s);
803
+ return resp.rows.map(x => ({
804
+ ..._.mapKeys(x, (_v, k) => _.camelCase(k)),
805
+ connectionData: x.connection_data ? safeJsonParse(x.connection_data, null) : null,
806
+ }));
807
+ },
808
+
809
+ getAuditLogDetail_meta: true,
810
+ async getAuditLogDetail({ id }) {
811
+ const [_conn, driver] = await getStorageConnection();
812
+ const res = await storageSelectFmt(
813
+ `select *
814
+ from ~audit_log
815
+ where ~audit_log.~id = %v`,
816
+ id
817
+ );
818
+ if (!res[0]) return null;
819
+ return {
820
+ ..._.mapKeys(res[0], (_v, k) => _.camelCase(k)),
821
+ connectionData: res[0].connection_data ? safeJsonParse(res[0].connection_data, null) : null,
822
+ };
823
+ },
824
+
702
825
  async getExportedDatabase() {
703
826
  const connections = await storageSelectFmt(`select * from ~connections`);
704
827
  const user_permissions = await storageSelectFmt(`select * from ~user_permissions`);
@@ -751,4 +874,10 @@ module.exports = {
751
874
  const resp = await storageSelectFmt(`select distinct ~engine from ~connections`);
752
875
  return resp.map(x => x.engine);
753
876
  },
877
+
878
+ sendAuditLog_meta: true,
879
+ async sendAuditLog(props, req) {
880
+ sendToAuditLog(req, props);
881
+ return null;
882
+ },
754
883
  };
@@ -7,6 +7,7 @@ const {
7
7
  extractErrorLogData,
8
8
  runQueryFmt,
9
9
  runQueryOnDriver,
10
+ adaptDatabaseInfo,
10
11
  } = require('dbgate-tools');
11
12
  const _ = require('lodash');
12
13
  const logger = getLogger('storageDb');
@@ -122,7 +123,8 @@ async function getStorageConnectionCore() {
122
123
  await dbgateApi.deployDb({
123
124
  systemConnection: newConnection,
124
125
  driver: storageDriver,
125
- loadedDbModel: storageModel,
126
+ // @ts-ignore
127
+ loadedDbModel: adaptDatabaseInfo(storageModel, storageDriver),
126
128
  targetSchema: process.env.STORAGE_SCHEMA,
127
129
  });
128
130