new config loading logic

- remove unused config files
- load all server env variables from ./config/env
- still define PWD as midwest seems to be using it
This commit is contained in:
Linus Miller 2020-08-28 20:42:15 +02:00
parent 3c5a05bed4
commit 6048991b2d
14 changed files with 71 additions and 201 deletions

View File

@ -34,7 +34,6 @@
"redux": "^4.0.5", "redux": "^4.0.5",
"redux-logger": "^3.0.6", "redux-logger": "^3.0.6",
"redux-thunk": "^2.2.0", "redux-thunk": "^2.2.0",
"require-dir": "^1.2.0",
"superagent": "^6.0.0", "superagent": "^6.0.0",
"useragent": "^2.1.12", "useragent": "^2.1.12",
"xml2json": "^0.12.0" "xml2json": "^0.12.0"

View File

@ -3,5 +3,5 @@
const p = require('path') const p = require('path')
module.exports = { module.exports = {
static: p.join(PWD, 'dist'), static: p.join(process.cwd(), 'dist'),
} }

30
server/config/env.js Normal file
View File

@ -0,0 +1,30 @@
'use strict'
function readFromEnv(columns, defaults) {
const missing = []
const result = columns.reduce((result, variable) => {
const value = (result[variable] = process.env[variable] || defaults[variable])
if (!value) {
missing.push(variable)
}
return result
}, {})
if (missing.length) {
throw new Error(`Missing required env variables: ${missing.join(', ')}`)
}
return result
}
const defaults = {
NODE_ENV: 'development',
POSTGRES_HOST: 'localhost',
}
module.exports = {
...readFromEnv(['NODE_ENV', 'POSTGRES_HOST'], defaults),
}

View File

@ -4,6 +4,8 @@ const _ = require('lodash')
const errorTemplate = require('../templates/Error') const errorTemplate = require('../templates/Error')
const env = require('./env')
const defaults = { const defaults = {
post: (req, res, next) => { post: (req, res, next) => {
res.template = errorTemplate res.template = errorTemplate
@ -50,5 +52,5 @@ module.exports = _.merge(
console: false, console: false,
}, },
}, },
}[ENV], }[env.NODE_ENV],
) )

View File

@ -1,4 +0,0 @@
'use strict'
// global.LOGIN_USER = 'linus.miller@bitmill.co';
// global.LOGIN_USER = 'zarac@zarac.se';

11
server/config/index.js Normal file
View File

@ -0,0 +1,11 @@
'use strict'
module.exports = {
dir: require('./dir'),
env: require('./env'),
errorHandler: require('./error_handler'),
port: require('./port'),
postgres: require('./postgres'),
shim: require('./shim'),
site: require('./site'),
}

View File

@ -1,108 +0,0 @@
'use strict'
const _ = require('lodash')
const config = {
site: require('./site'),
}
module.exports = {
invite: {
from: `${config.site.title} Robot <${config.site.emails.robot}>`,
subject: `You have been invited to ${config.site.title}`,
},
changePassword: {
from: `${config.site.title} Robot <${config.site.emails.robot}>`,
subject: `Password Reset Request for ${config.site.title}`,
},
timeouts: {
// 1 day
changePassword: 24 * 60 * 60 * 1000,
// verify email
verifyEmail: 7 * 24 * 60 * 60 * 1000,
},
paths: {
register: '/register',
login: '/login',
forgotPassword: '/forgot',
resetPassword: '/reset',
verifyEmail: '/verify',
},
redirects: {
login: '/',
logout: '/login',
register: '/login',
},
remember: {
// if expires is defined, it will be used. otherwise maxage
expires: new Date('2038-01-19T03:14:07.000Z'),
// expires: Date.now() - 1,
maxAge: 30 * 24 * 60 * 60 * 1000,
},
messages: {
login: {
notLocal: 'Account requires external login.',
wrongPassword: 'Wrong password.',
noUserFound: 'No user registered with that email.',
noExternalUser: 'The account is not connected to this website.',
externalLoginFailed: 'External login failed.',
emailNotVerified: "This account's email has not been verified.",
banned: 'User is banned.',
blocked: 'User is blocked due to too many login attempts.',
},
register: {
missingProperties: 'Oh no missing stuff',
notAuthorized: 'The email is not authorized to create an account.',
duplicateEmail: 'The email has already been registered.',
},
},
passport: {
local: {
usernameField: 'email',
},
scope: ['email'],
//providers: {
// facebook: {
// clientID: 'change-this-fool',
// clientSecret: 'change-this-fool',
// callbackURL: p.join(config.site.domain, '/auth/facebook/callback'),
// passReqToCallback: true
// },
},
userColumns: [
'givenName',
'familyName',
'dateBanned',
'dateBlocked',
'dateMuted',
'dateVerified',
// ['array(SELECT name FROM user_roles LEFT OUTER JOIN roles ON user_roles.role_id = roles.id WHERE user_roles.user_id = users.id)', 'roles'],
[
`(SELECT array_to_json(array_agg(row_to_json(d)))
FROM (
SELECT id, name
FROM user_roles
LEFT OUTER JOIN roles ON user_roles.role_id = roles.id WHERE user_roles.user_id = users.id
ORDER BY roles.id DESC
) d
)`,
'roles',
],
],
// needs to be even
tokenLength: 64,
// needs to be even
saltLength: 16,
}

View File

@ -1,5 +1,7 @@
'use strict' 'use strict'
const env = require('./env')
const basePort = 3060 const basePort = 3060
module.exports = { module.exports = {
@ -7,4 +9,4 @@ module.exports = {
testing: basePort + 1, testing: basePort + 1,
staging: basePort + 2, staging: basePort + 2,
production: basePort + 3, production: basePort + 3,
}[ENV] }[env.NODE_ENV]

View File

@ -1,6 +1,8 @@
import env from './env' 'use strict'
export default { const env = require('./env')
module.exports = {
database: 'journey', database: 'journey',
user: 'journey', user: 'journey',
password: 'journey', password: 'journey',

View File

@ -1,38 +0,0 @@
'use strict'
const chalk = require('chalk')
const session = require('express-session')
let redisStore
const config = {
secret:
'asdfpoi7u987777777777777777777sdkafjxxjasdhfhsadfhashdfh`1111111khjjashdfkasjhdflGGGGGGGGGGaaa^^^^^^^^^^yaghsdfqw3u7679`',
resave: false,
saveUninitialized: true,
}
const redisConfig = {
host: 'localhost',
port: 6379,
}
if (ENV === 'production') {
const RedisStore = require('connect-redis')(require('express-session'))
redisStore = new RedisStore(redisConfig)
redisStore.on('connect', () => {
console.info(`[${chalk.cyan('INIT')}] Redis connected succcessfully`)
})
redisStore.on('disconnect', () => {
throw new Error('Unable to connect to redis. Has it been started?')
})
config.store = redisStore
} else {
config.store = new session.MemoryStore()
}
module.exports = config

View File

@ -1,13 +1,14 @@
'use strict' 'use strict'
const _ = require('lodash') const _ = require('lodash')
const env = require('./env')
const domain = 'newseri.com' const domain = 'journey.bitmill.io'
const defaults = { const defaults = {
domain, domain,
title: 'Newseri Admin', title: 'Journey',
name: 'newseri-admin', name: 'journey',
protocol: 'http', protocol: 'http',
get host() { get host() {
return this.port ? this.hostname + ':' + this.port : this.hostname return this.port ? this.hostname + ':' + this.port : this.hostname
@ -16,10 +17,9 @@ const defaults = {
return this.protocol + '://' + this.host + '/' return this.protocol + '://' + this.host + '/'
}, },
emails: { emails: {
robot: 'no-reply@thecodebureau.com', robot: 'no-reply@bitmill.io',
info: 'info@thecodebureau.com', info: 'info@bitmill.io',
webmaster: 'webmaster@thecodebureau.com', webmaster: 'webmaster@tbitmill.io',
order: 'info@thecodebureau.com',
}, },
} }
@ -43,12 +43,6 @@ module.exports = _.merge(
production: { production: {
hostname: `admin.${domain}`, hostname: `admin.${domain}`,
protocol: 'https', protocol: 'https',
// emails: {
// robot: 'no-reply@' + domain,
// info: 'info@' + domain,
// webmaster: 'webmaster@' + domain,
// order: 'order@' + domain,
// },
}, },
}[ENV], }[env.NODE_ENV],
) )

View File

@ -1,15 +0,0 @@
'use strict'
const _ = require('lodash')
const defaults = {
auth: {
user: 'SMTP_Injection',
// dev key
pass: '2eec390c5b3f5d593c9f152179bf51e90b073784',
},
host: 'smtp.sparkpostmail.com',
port: 587,
}
module.exports = _.merge(defaults, {}[ENV])

View File

@ -7,24 +7,24 @@
* @type {Express instance} * @type {Express instance}
*/ */
global.ENV = process.env.NODE_ENV || 'development'
global.PWD = process.env.NODE_PWD || process.cwd() global.PWD = process.env.NODE_PWD || process.cwd()
const config = require('./config')
// modules > native // modules > native
const p = require('path') const p = require('path')
if (ENV === 'development') { if (config.env.NODE_ENV === 'development') {
// output filename in console log and colour console.dir // output filename in console log and colour console.dir
require('midwest/util/console') require('midwest/util/console')
// needed so symlinked modules get access to main projects node_modules/ // needed so symlinked modules get access to main projects node_modules/
require('app-module-path').addPath(p.join(PWD, 'node_modules')) require('app-module-path').addPath(p.join(process.cwd(), 'node_modules'))
} }
// modules > 3rd party // modules > 3rd party
const _ = require('lodash') const _ = require('lodash')
const chalk = require('chalk') const chalk = require('chalk')
const express = require('express') const express = require('express')
const requireDir = require('require-dir')
// modules > express middlewares // modules > express middlewares
const bodyParser = require('body-parser') const bodyParser = require('body-parser')
@ -43,15 +43,13 @@ process.on('uncaughtException', (err) => {
process.exit(1) process.exit(1)
}) })
const config = requireDir('./config', { mapKey: (value, key) => _.camelCase(key) })
const prewares = [ const prewares = [
express.static(config.dir.static, ENV === 'production' ? { maxAge: '1 year' } : null), express.static(config.dir.static, config.env.NODE_ENV === 'production' ? { maxAge: '1 year' } : null),
bodyParser.json(), bodyParser.json(),
bodyParser.urlencoded({ extended: true }), bodyParser.urlencoded({ extended: true }),
] ]
if (ENV === 'development') { if (config.env.NODE_ENV === 'development') {
// only log requests to console in development mode // only log requests to console in development mode
prewares.unshift(require('morgan')('dev')) prewares.unshift(require('morgan')('dev'))
// prewares.push(require('midwest-module-membership/passport/automatic-login')); // prewares.push(require('midwest-module-membership/passport/automatic-login'));
@ -83,11 +81,11 @@ server.response.render = function (template) {
} }
try { try {
server.locals.js = require(p.join(PWD, 'public/js.json')) server.locals.js = require(p.join(process.cwd(), 'public/js.json'))
} catch (e) {} } catch (e) {}
try { try {
server.locals.css = require(p.join(PWD, 'public/css.json')) server.locals.css = require(p.join(process.cwd(), 'public/css.json'))
} catch (e) {} } catch (e) {}
// load prewares // load prewares
@ -105,7 +103,9 @@ server.use(...postwares)
if (require.main === module) { if (require.main === module) {
server.http = server.listen(config.port, () => { server.http = server.listen(config.port, () => {
console.info( console.info(
`[${chalk.cyan('INIT')}] HTTP Server listening on port ${chalk.magenta(config.port)} (${chalk.yellow(ENV)})`, `[${chalk.cyan('INIT')}] HTTP Server listening on port ${chalk.magenta(config.port)} (${chalk.yellow(
config.env.NODE_ENV,
)})`,
) )
}) })
} }

View File

@ -6262,11 +6262,6 @@ repeat-string@^1.6.1:
resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637"
integrity sha1-jcrkcOHIirwtYA//Sndihtp15jc= integrity sha1-jcrkcOHIirwtYA//Sndihtp15jc=
require-dir@^1.2.0:
version "1.2.0"
resolved "https://registry.yarnpkg.com/require-dir/-/require-dir-1.2.0.tgz#0d443b75e96012d3ca749cf19f529a789ae74817"
integrity sha512-LY85DTSu+heYgDqq/mK+7zFHWkttVNRXC9NKcKGyuGLdlsfbjEPrIEYdCVrx6hqnJb+xSu3Lzaoo8VnmOhhjNA==
require-directory@^2.1.1: require-directory@^2.1.1:
version "2.1.1" version "2.1.1"
resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42"