From cc46d72c53e164dfd5b767a00953b38e53209ed8 Mon Sep 17 00:00:00 2001 From: ChengLei Shao Date: Mon, 11 Sep 2023 10:55:47 +0800 Subject: [PATCH] feat(database): support ssl config of database (#2620) * feat: support ssl config of database * chore: .env.example --- .env.example | 6 +++++ packages/core/app/src/config/database.ts | 31 +++++++++++++++++++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/.env.example b/.env.example index d70efc28a6..c2545bd57c 100644 --- a/.env.example +++ b/.env.example @@ -36,6 +36,12 @@ DB_TABLE_PREFIX= # DB_LOGGING=on # DB_UNDERSCORED=false +#== SSL CONFIG ==# +# DB_DIALECT_OPTIONS_SSL_CA= +# DB_DIALECT_OPTIONS_SSL_KEY= +# DB_DIALECT_OPTIONS_SSL_CERT= +# DB_DIALECT_OPTIONS_SSL_REJECT_UNAUTHORIZED=true + ################# CACHE ################# # default is memory cache, when develop mode,code's change will be clear memory cache, so can use 'cache-manager-fs-hash' # CACHE_CONFIG={"storePackage":"cache-manager-fs-hash","ttl":86400,"max":1000} diff --git a/packages/core/app/src/config/database.ts b/packages/core/app/src/config/database.ts index 6d40838aef..d573e219c8 100644 --- a/packages/core/app/src/config/database.ts +++ b/packages/core/app/src/config/database.ts @@ -1,6 +1,26 @@ import { IDatabaseOptions } from '@nocobase/database'; -export default { +function getEnvValue(key, defaultValue?) { + return process.env[key] || defaultValue; +} + +function extractSSLOptionsFromEnv() { + const sslOptions = {}; + + const ca = getEnvValue('DB_DIALECT_OPTIONS_SSL_CA'); + const key = getEnvValue('DB_DIALECT_OPTIONS_SSL_KEY'); + const cert = getEnvValue('DB_DIALECT_OPTIONS_SSL_CERT'); + const rejectUnauthorized = getEnvValue('DB_DIALECT_OPTIONS_SSL_REJECT_UNAUTHORIZED'); + + if (ca) sslOptions['ca'] = ca; + if (key) sslOptions['key'] = key; + if (cert) sslOptions['cert'] = cert; + if (rejectUnauthorized) sslOptions['rejectUnauthorized'] = rejectUnauthorized === 'true'; + + return sslOptions; +} + +const databaseOptions = { logging: process.env.DB_LOGGING == 'on' ? customLogger : false, dialect: process.env.DB_DIALECT as any, storage: process.env.DB_STORAGE, @@ -15,6 +35,15 @@ export default { underscored: process.env.DB_UNDERSCORED === 'true', } as IDatabaseOptions; +const sslOptions = extractSSLOptionsFromEnv(); + +if (Object.keys(sslOptions).length) { + databaseOptions.dialectOptions = databaseOptions.dialectOptions || {}; + databaseOptions.dialectOptions['ssl'] = sslOptions; +} + +export default databaseOptions; + function customLogger(queryString, queryObject) { console.log(queryString); // outputs a string if (queryObject?.bind) {