configure.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. const path = require('path')
  2. /* global wiki */
  3. module.exports = () => {
  4. // ----------------------------------------
  5. // Load modules
  6. // ----------------------------------------
  7. const bodyParser = require('body-parser')
  8. const compression = require('compression')
  9. const express = require('express')
  10. const favicon = require('serve-favicon')
  11. const http = require('http')
  12. const Promise = require('bluebird')
  13. const fs = Promise.promisifyAll(require('fs-extra'))
  14. const yaml = require('js-yaml')
  15. const _ = require('lodash')
  16. const cfgHelper = require('./helpers/config')
  17. // ----------------------------------------
  18. // Define Express App
  19. // ----------------------------------------
  20. let app = express()
  21. app.use(compression())
  22. let server
  23. // ----------------------------------------
  24. // Public Assets
  25. // ----------------------------------------
  26. app.use(favicon(path.join(wiki.ROOTPATH, 'assets', 'favicon.ico')))
  27. app.use(express.static(path.join(wiki.ROOTPATH, 'assets')))
  28. // ----------------------------------------
  29. // View Engine Setup
  30. // ----------------------------------------
  31. app.set('views', path.join(wiki.SERVERPATH, 'views'))
  32. app.set('view engine', 'pug')
  33. app.use(bodyParser.json())
  34. app.use(bodyParser.urlencoded({ extended: false }))
  35. app.locals.config = wiki.config
  36. app.locals.data = wiki.data
  37. app.locals._ = require('lodash')
  38. // ----------------------------------------
  39. // Controllers
  40. // ----------------------------------------
  41. app.get('*', (req, res) => {
  42. fs.readJsonAsync(path.join(wiki.ROOTPATH, 'package.json')).then(packageObj => {
  43. res.render('configure/index', { packageObj })
  44. })
  45. })
  46. /**
  47. * Perform basic system checks
  48. */
  49. app.post('/syscheck', (req, res) => {
  50. Promise.mapSeries([
  51. () => {
  52. const semver = require('semver')
  53. if (!semver.satisfies(semver.clean(process.version), '>=6.11.1')) {
  54. throw new Error('Node.js version is too old. Minimum is 6.11.1.')
  55. }
  56. return 'Node.js ' + process.version + ' detected. Minimum is 6.11.1.'
  57. },
  58. () => {
  59. return Promise.try(() => {
  60. require('crypto')
  61. }).catch(err => {
  62. throw new Error('Crypto Node.js module is not available.')
  63. }).return('Node.js Crypto module is available.')
  64. },
  65. () => {
  66. const exec = require('child_process').exec
  67. const semver = require('semver')
  68. return new Promise((resolve, reject) => {
  69. exec('git --version', (err, stdout, stderr) => {
  70. if (err || stdout.length < 3) {
  71. reject(new Error('Git is not installed or not reachable from PATH.'))
  72. }
  73. let gitver = _.head(stdout.match(/[\d]+\.[\d]+(\.[\d]+)?/gi))
  74. if (!gitver || !semver.satisfies(semver.clean(gitver), '>=2.7.4')) {
  75. reject(new Error('Git version is too old. Minimum is 2.7.4.'))
  76. }
  77. resolve('Git ' + gitver + ' detected. Minimum is 2.7.4.')
  78. })
  79. })
  80. },
  81. () => {
  82. const os = require('os')
  83. if (os.totalmem() < 1000 * 1000 * 512) {
  84. throw new Error('Not enough memory. Minimum is 512 MB.')
  85. }
  86. return _.round(os.totalmem() / (1024 * 1024)) + ' MB of system memory available. Minimum is 512 MB.'
  87. },
  88. () => {
  89. let fs = require('fs')
  90. return Promise.try(() => {
  91. fs.accessSync(path.join(wiki.ROOTPATH, 'config.yml'), (fs.constants || fs).W_OK)
  92. }).catch(err => {
  93. throw new Error('config.yml file is not writable by Node.js process or was not created properly.')
  94. }).return('config.yml is writable by the setup process.')
  95. }
  96. ], test => { return test() }).then(results => {
  97. res.json({ ok: true, results })
  98. }).catch(err => {
  99. res.json({ ok: false, error: err.message })
  100. })
  101. })
  102. /**
  103. * Check the Git connection
  104. */
  105. app.post('/gitcheck', (req, res) => {
  106. const exec = require('execa')
  107. const url = require('url')
  108. const dataDir = path.resolve(wiki.ROOTPATH, cfgHelper.parseConfigValue(req.body.pathData))
  109. const gitDir = path.resolve(wiki.ROOTPATH, cfgHelper.parseConfigValue(req.body.pathRepo))
  110. let gitRemoteUrl = ''
  111. if (req.body.gitUseRemote === true) {
  112. let urlObj = url.parse(cfgHelper.parseConfigValue(req.body.gitUrl))
  113. if (req.body.gitAuthType === 'basic') {
  114. urlObj.auth = req.body.gitAuthUser + ':' + req.body.gitAuthPass
  115. }
  116. gitRemoteUrl = url.format(urlObj)
  117. }
  118. Promise.mapSeries([
  119. () => {
  120. return fs.ensureDirAsync(dataDir).return('Data directory path is valid.')
  121. },
  122. () => {
  123. return fs.ensureDirAsync(gitDir).return('Git directory path is valid.')
  124. },
  125. () => {
  126. return exec.stdout('git', ['init'], { cwd: gitDir }).then(result => {
  127. return 'Local git repository has been initialized.'
  128. })
  129. },
  130. () => {
  131. if (req.body.gitUseRemote === false) { return false }
  132. return exec.stdout('git', ['config', '--local', 'user.name', 'Wiki'], { cwd: gitDir }).then(result => {
  133. return 'Git Signature Name has been set successfully.'
  134. })
  135. },
  136. () => {
  137. if (req.body.gitUseRemote === false) { return false }
  138. return exec.stdout('git', ['config', '--local', 'user.email', req.body.gitServerEmail], { cwd: gitDir }).then(result => {
  139. return 'Git Signature Name has been set successfully.'
  140. })
  141. },
  142. () => {
  143. if (req.body.gitUseRemote === false) { return false }
  144. return exec.stdout('git', ['config', '--local', '--bool', 'http.sslVerify', req.body.gitAuthSSL], { cwd: gitDir }).then(result => {
  145. return 'Git SSL Verify flag has been set successfully.'
  146. })
  147. },
  148. () => {
  149. if (req.body.gitUseRemote === false) { return false }
  150. if (req.body.gitAuthType === 'ssh') {
  151. return exec.stdout('git', ['config', '--local', 'core.sshCommand', 'ssh -i "' + req.body.gitAuthSSHKey + '" -o StrictHostKeyChecking=no'], { cwd: gitDir }).then(result => {
  152. return 'Git SSH Private Key path has been set successfully.'
  153. })
  154. } else {
  155. return false
  156. }
  157. },
  158. () => {
  159. if (req.body.gitUseRemote === false) { return false }
  160. return exec.stdout('git', ['remote', 'rm', 'origin'], { cwd: gitDir }).catch(err => {
  161. if (_.includes(err.message, 'No such remote') || _.includes(err.message, 'Could not remove')) {
  162. return true
  163. } else {
  164. throw err
  165. }
  166. }).then(() => {
  167. return exec.stdout('git', ['remote', 'add', 'origin', gitRemoteUrl], { cwd: gitDir }).then(result => {
  168. return 'Git Remote was added successfully.'
  169. })
  170. })
  171. },
  172. () => {
  173. if (req.body.gitUseRemote === false) { return false }
  174. return exec.stdout('git', ['pull', 'origin', req.body.gitBranch], { cwd: gitDir }).then(result => {
  175. return 'Git Pull operation successful.'
  176. })
  177. }
  178. ], step => { return step() }).then(results => {
  179. return res.json({ ok: true, results: _.without(results, false) })
  180. }).catch(err => {
  181. let errMsg = (err.stderr) ? err.stderr.replace(/(error:|warning:|fatal:)/gi, '').replace(/ \s+/g, ' ') : err.message
  182. res.json({ ok: false, error: errMsg })
  183. })
  184. })
  185. /**
  186. * Finalize
  187. */
  188. app.post('/finalize', (req, res) => {
  189. const bcrypt = require('bcryptjs-then')
  190. const crypto = Promise.promisifyAll(require('crypto'))
  191. let mongo = require('mongodb').MongoClient
  192. let parsedMongoConStr = cfgHelper.parseConfigValue(req.body.db)
  193. Promise.join(
  194. new Promise((resolve, reject) => {
  195. mongo.connect(parsedMongoConStr, {
  196. autoReconnect: false,
  197. reconnectTries: 2,
  198. reconnectInterval: 1000,
  199. connectTimeoutMS: 5000,
  200. socketTimeoutMS: 5000
  201. }, (err, db) => {
  202. if (err === null) {
  203. db.createCollection('users', { strict: false }, (err, results) => {
  204. if (err === null) {
  205. bcrypt.hash(req.body.adminPassword).then(adminPwdHash => {
  206. db.collection('users').findOneAndUpdate({
  207. provider: 'local',
  208. email: req.body.adminEmail
  209. }, {
  210. provider: 'local',
  211. email: req.body.adminEmail,
  212. name: 'Administrator',
  213. password: adminPwdHash,
  214. rights: [{
  215. role: 'admin',
  216. path: '/',
  217. exact: false,
  218. deny: false
  219. }],
  220. updatedAt: new Date(),
  221. createdAt: new Date()
  222. }, {
  223. upsert: true,
  224. returnOriginal: false
  225. }, (err, results) => {
  226. if (err === null) {
  227. resolve(true)
  228. } else {
  229. reject(err)
  230. }
  231. db.close()
  232. })
  233. })
  234. } else {
  235. reject(err)
  236. db.close()
  237. }
  238. })
  239. } else {
  240. reject(err)
  241. }
  242. })
  243. }),
  244. fs.readFileAsync(path.join(wiki.ROOTPATH, 'config.yml'), 'utf8').then(confRaw => {
  245. let conf = yaml.safeLoad(confRaw)
  246. conf.title = req.body.title
  247. conf.host = req.body.host
  248. conf.port = req.body.port
  249. conf.paths = {
  250. repo: req.body.pathRepo,
  251. data: req.body.pathData
  252. }
  253. conf.uploads = {
  254. maxImageFileSize: (conf.uploads && _.isNumber(conf.uploads.maxImageFileSize)) ? conf.uploads.maxImageFileSize : 3,
  255. maxOtherFileSize: (conf.uploads && _.isNumber(conf.uploads.maxOtherFileSize)) ? conf.uploads.maxOtherFileSize : 100
  256. }
  257. conf.lang = req.body.lang
  258. conf.public = (req.body.public === true)
  259. if (conf.auth && conf.auth.local) {
  260. conf.auth.local = { enabled: true }
  261. } else {
  262. conf.auth = { local: { enabled: true } }
  263. }
  264. conf.db = req.body.db
  265. if (req.body.gitUseRemote === false) {
  266. conf.git = false
  267. } else {
  268. conf.git = {
  269. url: req.body.gitUrl,
  270. branch: req.body.gitBranch,
  271. auth: {
  272. type: req.body.gitAuthType,
  273. username: req.body.gitAuthUser,
  274. password: req.body.gitAuthPass,
  275. privateKey: req.body.gitAuthSSHKey,
  276. sslVerify: (req.body.gitAuthSSL === true)
  277. },
  278. showUserEmail: (req.body.gitShowUserEmail === true),
  279. serverEmail: req.body.gitServerEmail
  280. }
  281. }
  282. return crypto.randomBytesAsync(32).then(buf => {
  283. conf.sessionSecret = buf.toString('hex')
  284. confRaw = yaml.safeDump(conf)
  285. return fs.writeFileAsync(path.join(wiki.ROOTPATH, 'config.yml'), confRaw)
  286. })
  287. })
  288. ).then(() => {
  289. if (process.env.IS_HEROKU) {
  290. return fs.outputJsonAsync(path.join(wiki.SERVERPATH, 'app/heroku.json'), { configured: true })
  291. } else {
  292. return true
  293. }
  294. }).then(() => {
  295. res.json({ ok: true })
  296. }).catch(err => {
  297. res.json({ ok: false, error: err.message })
  298. })
  299. })
  300. /**
  301. * Restart in normal mode
  302. */
  303. app.post('/restart', (req, res) => {
  304. res.status(204).end()
  305. /* server.destroy(() => {
  306. spinner.text = 'Setup wizard terminated. Restarting in normal mode...'
  307. _.delay(() => {
  308. const exec = require('execa')
  309. exec.stdout('node', ['wiki', 'start']).then(result => {
  310. spinner.succeed('Wiki.js is now running in normal mode!')
  311. process.exit(0)
  312. })
  313. }, 1000)
  314. }) */
  315. })
  316. // ----------------------------------------
  317. // Error handling
  318. // ----------------------------------------
  319. app.use(function (req, res, next) {
  320. var err = new Error('Not Found')
  321. err.status = 404
  322. next(err)
  323. })
  324. app.use(function (err, req, res, next) {
  325. res.status(err.status || 500)
  326. res.send({
  327. message: err.message,
  328. error: wiki.IS_DEBUG ? err : {}
  329. })
  330. wiki.logger.error(err.message)
  331. process.exit(1)
  332. })
  333. // ----------------------------------------
  334. // Start HTTP server
  335. // ----------------------------------------
  336. wiki.logger.info(`HTTP Server on port: ${wiki.config.port}`)
  337. app.set('port', wiki.config.port)
  338. server = http.createServer(app)
  339. server.listen(wiki.config.port)
  340. var openConnections = []
  341. server.on('connection', (conn) => {
  342. let key = conn.remoteAddress + ':' + conn.remotePort
  343. openConnections[key] = conn
  344. conn.on('close', () => {
  345. delete openConnections[key]
  346. })
  347. })
  348. server.destroy = (cb) => {
  349. server.close(cb)
  350. for (let key in openConnections) {
  351. openConnections[key].destroy()
  352. }
  353. }
  354. server.on('error', (error) => {
  355. if (error.syscall !== 'listen') {
  356. throw error
  357. }
  358. switch (error.code) {
  359. case 'EACCES':
  360. wiki.logger.error('Listening on port ' + wiki.config.port + ' requires elevated privileges!')
  361. return process.exit(1)
  362. case 'EADDRINUSE':
  363. wiki.logger.error('Port ' + wiki.config.port + ' is already in use!')
  364. return process.exit(1)
  365. default:
  366. throw error
  367. }
  368. })
  369. server.on('listening', () => {
  370. wiki.logger.info('HTTP Server: RUNNING')
  371. })
  372. }