Skip to content

Commit 2a07445

Browse files
committedMar 21, 2023
Refactor configuration
- No longer use config npm package - Prefer config from env vars, though still has support for config file - No longer writes a config file for database config - Writes keys to a new file in /data folder - Removes a lot of cruft and improves config understanding
1 parent dad3e1d commit 2a07445

File tree

13 files changed

+278
-261
lines changed

13 files changed

+278
-261
lines changed
 

‎backend/app.js

+4-3
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ const express = require('express');
22
const bodyParser = require('body-parser');
33
const fileUpload = require('express-fileupload');
44
const compression = require('compression');
5+
const config = require('./lib/config');
56
const log = require('./logger').express;
67

78
/**
@@ -24,7 +25,7 @@ app.enable('trust proxy', ['loopback', 'linklocal', 'uniquelocal']);
2425
app.enable('strict routing');
2526

2627
// pretty print JSON when not live
27-
if (process.env.NODE_ENV !== 'production') {
28+
if (config.debug()) {
2829
app.set('json spaces', 2);
2930
}
3031

@@ -65,7 +66,7 @@ app.use(function (err, req, res, next) {
6566
}
6667
};
6768

68-
if (process.env.NODE_ENV === 'development' || (req.baseUrl + req.path).includes('nginx/certificates')) {
69+
if (config.debug() || (req.baseUrl + req.path).includes('nginx/certificates')) {
6970
payload.debug = {
7071
stack: typeof err.stack !== 'undefined' && err.stack ? err.stack.split('\n') : null,
7172
previous: err.previous
@@ -74,7 +75,7 @@ app.use(function (err, req, res, next) {
7475

7576
// Not every error is worth logging - but this is good for now until it gets annoying.
7677
if (typeof err.stack !== 'undefined' && err.stack) {
77-
if (process.env.NODE_ENV === 'development' || process.env.DEBUG) {
78+
if (config.debug()) {
7879
log.debug(err.stack);
7980
} else if (typeof err.public == 'undefined' || !err.public) {
8081
log.warn(err.message);

‎backend/db.js

+20-26
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,27 @@
1-
const config = require('config');
1+
const config = require('./lib/config');
22

33
if (!config.has('database')) {
4-
throw new Error('Database config does not exist! Please read the instructions: https://github.com/jc21/nginx-proxy-manager/blob/master/doc/INSTALL.md');
4+
throw new Error('Database config does not exist! Please read the instructions: https://nginxproxymanager.com/setup/');
55
}
66

77
function generateDbConfig() {
8-
if (config.database.engine === 'knex-native') {
9-
return config.database.knex;
10-
} else
11-
return {
12-
client: config.database.engine,
13-
connection: {
14-
host: config.database.host,
15-
user: config.database.user,
16-
password: config.database.password,
17-
database: config.database.name,
18-
port: config.database.port
19-
},
20-
migrations: {
21-
tableName: 'migrations'
22-
}
23-
};
8+
const cfg = config.get('database');
9+
if (cfg.engine === 'knex-native') {
10+
return cfg.knex;
11+
}
12+
return {
13+
client: cfg.engine,
14+
connection: {
15+
host: cfg.host,
16+
user: cfg.user,
17+
password: cfg.password,
18+
database: cfg.name,
19+
port: cfg.port
20+
},
21+
migrations: {
22+
tableName: 'migrations'
23+
}
24+
};
2425
}
2526

26-
27-
let data = generateDbConfig();
28-
29-
if (typeof config.database.version !== 'undefined') {
30-
data.version = config.database.version;
31-
}
32-
33-
module.exports = require('knex')(data);
27+
module.exports = require('knex')(generateDbConfig());

‎backend/index.js

+1-87
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
#!/usr/bin/env node
22

3+
const fs = require('fs');
34
const logger = require('./logger').global;
45

56
async function appStart () {
6-
// Create config file db settings if environment variables have been set
7-
await createDbConfigFromEnvironment();
8-
97
const migrate = require('./migrate');
108
const setup = require('./setup');
119
const app = require('./app');
@@ -42,90 +40,6 @@ async function appStart () {
4240
});
4341
}
4442

45-
async function createDbConfigFromEnvironment() {
46-
return new Promise((resolve, reject) => {
47-
const envMysqlHost = process.env.DB_MYSQL_HOST || null;
48-
const envMysqlPort = process.env.DB_MYSQL_PORT || null;
49-
const envMysqlUser = process.env.DB_MYSQL_USER || null;
50-
const envMysqlName = process.env.DB_MYSQL_NAME || null;
51-
let envSqliteFile = process.env.DB_SQLITE_FILE || null;
52-
53-
const fs = require('fs');
54-
const filename = (process.env.NODE_CONFIG_DIR || './config') + '/' + (process.env.NODE_ENV || 'default') + '.json';
55-
let configData = {};
56-
57-
try {
58-
configData = require(filename);
59-
} catch (err) {
60-
// do nothing
61-
}
62-
63-
if (configData.database && configData.database.engine && !configData.database.fromEnv) {
64-
logger.info('Manual db configuration already exists, skipping config creation from environment variables');
65-
resolve();
66-
return;
67-
}
68-
69-
if ((!envMysqlHost || !envMysqlPort || !envMysqlUser || !envMysqlName) && !envSqliteFile){
70-
envSqliteFile = '/data/database.sqlite';
71-
logger.info(`No valid environment variables for database provided, using default SQLite file '${envSqliteFile}'`);
72-
}
73-
74-
if (envMysqlHost && envMysqlPort && envMysqlUser && envMysqlName) {
75-
const newConfig = {
76-
fromEnv: true,
77-
engine: 'mysql',
78-
host: envMysqlHost,
79-
port: envMysqlPort,
80-
user: envMysqlUser,
81-
password: process.env.DB_MYSQL_PASSWORD,
82-
name: envMysqlName,
83-
};
84-
85-
if (JSON.stringify(configData.database) === JSON.stringify(newConfig)) {
86-
// Config is unchanged, skip overwrite
87-
resolve();
88-
return;
89-
}
90-
91-
logger.info('Generating MySQL knex configuration from environment variables');
92-
configData.database = newConfig;
93-
94-
} else {
95-
const newConfig = {
96-
fromEnv: true,
97-
engine: 'knex-native',
98-
knex: {
99-
client: 'sqlite3',
100-
connection: {
101-
filename: envSqliteFile
102-
},
103-
useNullAsDefault: true
104-
}
105-
};
106-
if (JSON.stringify(configData.database) === JSON.stringify(newConfig)) {
107-
// Config is unchanged, skip overwrite
108-
resolve();
109-
return;
110-
}
111-
112-
logger.info('Generating SQLite knex configuration');
113-
configData.database = newConfig;
114-
}
115-
116-
// Write config
117-
fs.writeFile(filename, JSON.stringify(configData, null, 2), (err) => {
118-
if (err) {
119-
logger.error('Could not write db config to config file: ' + filename);
120-
reject(err);
121-
} else {
122-
logger.debug('Wrote db configuration to config file: ' + filename);
123-
resolve();
124-
}
125-
});
126-
});
127-
}
128-
12943
try {
13044
appStart();
13145
} catch (err) {

‎backend/internal/certificate.js

+19-17
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,24 @@
1-
const _ = require('lodash');
2-
const fs = require('fs');
3-
const https = require('https');
4-
const tempWrite = require('temp-write');
5-
const moment = require('moment');
6-
const logger = require('../logger').ssl;
7-
const error = require('../lib/error');
8-
const utils = require('../lib/utils');
9-
const certificateModel = require('../models/certificate');
10-
const dnsPlugins = require('../global/certbot-dns-plugins');
11-
const internalAuditLog = require('./audit-log');
12-
const internalNginx = require('./nginx');
13-
const internalHost = require('./host');
14-
const letsencryptStaging = process.env.NODE_ENV !== 'production';
1+
const _ = require('lodash');
2+
const fs = require('fs');
3+
const https = require('https');
4+
const tempWrite = require('temp-write');
5+
const moment = require('moment');
6+
const logger = require('../logger').ssl;
7+
const config = require('../lib/config');
8+
const error = require('../lib/error');
9+
const utils = require('../lib/utils');
10+
const certificateModel = require('../models/certificate');
11+
const dnsPlugins = require('../global/certbot-dns-plugins');
12+
const internalAuditLog = require('./audit-log');
13+
const internalNginx = require('./nginx');
14+
const internalHost = require('./host');
15+
const archiver = require('archiver');
16+
const path = require('path');
17+
const { isArray } = require('lodash');
18+
19+
const letsencryptStaging = config.useLetsencryptStaging();
1520
const letsencryptConfig = '/etc/letsencrypt.ini';
1621
const certbotCommand = 'certbot';
17-
const archiver = require('archiver');
18-
const path = require('path');
19-
const { isArray } = require('lodash');
2022

2123
function omissions() {
2224
return ['is_deleted'];

‎backend/internal/nginx.js

+16-16
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
const _ = require('lodash');
2-
const fs = require('fs');
3-
const logger = require('../logger').nginx;
4-
const utils = require('../lib/utils');
5-
const error = require('../lib/error');
6-
const debug_mode = process.env.NODE_ENV !== 'production' || !!process.env.DEBUG;
1+
const _ = require('lodash');
2+
const fs = require('fs');
3+
const logger = require('../logger').nginx;
4+
const config = require('../lib/config');
5+
const utils = require('../lib/utils');
6+
const error = require('../lib/error');
77

88
const internalNginx = {
99

@@ -65,7 +65,7 @@ const internalNginx = {
6565
}
6666
});
6767

68-
if (debug_mode) {
68+
if (config.debug()) {
6969
logger.error('Nginx test failed:', valid_lines.join('\n'));
7070
}
7171

@@ -101,7 +101,7 @@ const internalNginx = {
101101
* @returns {Promise}
102102
*/
103103
test: () => {
104-
if (debug_mode) {
104+
if (config.debug()) {
105105
logger.info('Testing Nginx configuration');
106106
}
107107

@@ -184,7 +184,7 @@ const internalNginx = {
184184
generateConfig: (host_type, host) => {
185185
const nice_host_type = internalNginx.getFileFriendlyHostType(host_type);
186186

187-
if (debug_mode) {
187+
if (config.debug()) {
188188
logger.info('Generating ' + nice_host_type + ' Config:', JSON.stringify(host, null, 2));
189189
}
190190

@@ -239,7 +239,7 @@ const internalNginx = {
239239
.then((config_text) => {
240240
fs.writeFileSync(filename, config_text, {encoding: 'utf8'});
241241

242-
if (debug_mode) {
242+
if (config.debug()) {
243243
logger.success('Wrote config:', filename, config_text);
244244
}
245245

@@ -249,7 +249,7 @@ const internalNginx = {
249249
resolve(true);
250250
})
251251
.catch((err) => {
252-
if (debug_mode) {
252+
if (config.debug()) {
253253
logger.warn('Could not write ' + filename + ':', err.message);
254254
}
255255

@@ -268,7 +268,7 @@ const internalNginx = {
268268
* @returns {Promise}
269269
*/
270270
generateLetsEncryptRequestConfig: (certificate) => {
271-
if (debug_mode) {
271+
if (config.debug()) {
272272
logger.info('Generating LetsEncrypt Request Config:', certificate);
273273
}
274274

@@ -292,14 +292,14 @@ const internalNginx = {
292292
.then((config_text) => {
293293
fs.writeFileSync(filename, config_text, {encoding: 'utf8'});
294294

295-
if (debug_mode) {
295+
if (config.debug()) {
296296
logger.success('Wrote config:', filename, config_text);
297297
}
298298

299299
resolve(true);
300300
})
301301
.catch((err) => {
302-
if (debug_mode) {
302+
if (config.debug()) {
303303
logger.warn('Could not write ' + filename + ':', err.message);
304304
}
305305

@@ -416,8 +416,8 @@ const internalNginx = {
416416
* @param {string} config
417417
* @returns {boolean}
418418
*/
419-
advancedConfigHasDefaultLocation: function (config) {
420-
return !!config.match(/^(?:.*;)?\s*?location\s*?\/\s*?{/im);
419+
advancedConfigHasDefaultLocation: function (cfg) {
420+
return !!cfg.match(/^(?:.*;)?\s*?location\s*?\/\s*?{/im);
421421
},
422422

423423
/**

0 commit comments

Comments
 (0)
Please sign in to comment.