wikijs-fork/server/setup.js

313 lines
9.1 KiB
JavaScript
Raw Normal View History

2017-10-08 21:21:36 +00:00
const path = require('path')
2017-02-26 23:06:20 +00:00
/* global WIKI */
2017-02-26 23:06:20 +00:00
2017-10-08 21:21:36 +00:00
module.exports = () => {
WIKI.config.site = {
path: '',
title: 'Wiki.js'
}
WIKI.system = require('./core/system')
2017-02-26 23:06:20 +00:00
// ----------------------------------------
// Load modules
// ----------------------------------------
const bodyParser = require('body-parser')
const compression = require('compression')
const express = require('express')
const favicon = require('serve-favicon')
const http = require('http')
2017-03-05 04:20:22 +00:00
const Promise = require('bluebird')
2018-09-02 02:37:20 +00:00
const fs = require('fs-extra')
2017-03-05 04:20:22 +00:00
const _ = require('lodash')
2017-05-15 00:17:08 +00:00
const cfgHelper = require('./helpers/config')
const crypto = Promise.promisifyAll(require('crypto'))
2017-02-26 23:06:20 +00:00
// ----------------------------------------
// Define Express App
// ----------------------------------------
2017-10-08 21:21:36 +00:00
let app = express()
2017-02-26 23:06:20 +00:00
app.use(compression())
// ----------------------------------------
// Public Assets
// ----------------------------------------
app.use(favicon(path.join(WIKI.ROOTPATH, 'assets', 'favicon.ico')))
app.use(express.static(path.join(WIKI.ROOTPATH, 'assets')))
2017-02-26 23:06:20 +00:00
// ----------------------------------------
// View Engine Setup
// ----------------------------------------
app.set('views', path.join(WIKI.SERVERPATH, 'views'))
2017-02-26 23:06:20 +00:00
app.set('view engine', 'pug')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.locals.config = WIKI.config
app.locals.data = WIKI.data
2017-02-26 23:06:20 +00:00
app.locals._ = require('lodash')
2018-01-28 02:40:51 +00:00
// ----------------------------------------
// HMR (Dev Mode Only)
// ----------------------------------------
if (global.DEV) {
app.use(global.WP_DEV.devMiddleware)
app.use(global.WP_DEV.hotMiddleware)
2018-01-28 02:40:51 +00:00
}
2017-02-26 23:06:20 +00:00
// ----------------------------------------
// Controllers
// ----------------------------------------
app.get('*', async (req, res) => {
let packageObj = await fs.readJson(path.join(WIKI.ROOTPATH, 'package.json'))
res.render('setup', {
packageObj,
telemetryClientID: WIKI.telemetry.cid
})
2017-02-26 23:06:20 +00:00
})
2017-03-25 21:03:09 +00:00
/**
* Finalize
2017-03-25 21:03:09 +00:00
*/
app.post('/finalize', async (req, res) => {
WIKI.telemetry.sendEvent('setup', 'finalize')
2017-10-23 01:58:07 +00:00
try {
// Upgrade from WIKI.js 1.x?
if (req.body.upgrade) {
await WIKI.system.upgradeFromMongo({
mongoCnStr: cfgHelper.parseConfigValue(req.body.upgMongo)
})
}
// Create directory structure
const dataPath = path.join(process.cwd(), 'data')
await fs.ensureDir(dataPath)
await fs.ensureDir(path.join(dataPath, 'cache'))
await fs.ensureDir(path.join(dataPath, 'uploads'))
2018-05-28 18:46:55 +00:00
// Set config
_.set(WIKI.config, 'defaultEditor', 'markdown')
2018-05-28 18:46:55 +00:00
_.set(WIKI.config, 'graphEndpoint', 'https://graph.requarks.io')
_.set(WIKI.config, 'lang.code', 'en')
_.set(WIKI.config, 'lang.autoUpdate', true)
_.set(WIKI.config, 'lang.namespacing', false)
_.set(WIKI.config, 'lang.namespaces', [])
_.set(WIKI.config, 'public', false)
2018-05-28 18:46:55 +00:00
_.set(WIKI.config, 'sessionSecret', (await crypto.randomBytesAsync(32)).toString('hex'))
_.set(WIKI.config, 'telemetry.isEnabled', req.body.telemetry === 'true')
_.set(WIKI.config, 'telemetry.clientId', WIKI.telemetry.cid)
2018-06-11 03:23:09 +00:00
_.set(WIKI.config, 'theming.theme', 'default')
_.set(WIKI.config, 'theming.darkMode', false)
_.set(WIKI.config, 'title', 'Wiki.js')
2017-12-17 04:41:16 +00:00
// Save config to DB
WIKI.logger.info('Persisting config to DB...')
await WIKI.configSvc.saveToDb([
'defaultEditor',
'graphEndpoint',
'lang',
'public',
'sessionSecret',
'telemetry',
2018-06-11 03:23:09 +00:00
'theming',
'title'
])
2017-12-17 04:41:16 +00:00
2018-05-20 22:50:51 +00:00
// Create default locale
WIKI.logger.info('Installing default locale...')
await WIKI.models.locales.query().insert({
2018-05-20 22:50:51 +00:00
code: 'en',
strings: require('./locales/default.json'),
isRTL: false,
name: 'English',
nativeName: 'English'
})
// Create default locale
WIKI.logger.info('Creating default groups...')
const adminGroup = await WIKI.models.groups.query().insert({
name: 'Administrators',
permissions: JSON.stringify(['manage:system']),
isSystem: true
})
const guestGroup = await WIKI.models.groups.query().insert({
name: 'Guests',
2018-10-14 21:38:39 +00:00
permissions: JSON.stringify(['read:pages']),
isSystem: true
})
2018-05-28 18:46:55 +00:00
// Load authentication strategies + enable local
await WIKI.models.authentication.refreshStrategiesFromDisk()
await WIKI.models.authentication.query().patch({ isEnabled: true }).where('key', 'local')
2018-05-28 18:46:55 +00:00
// Load editors + enable default
await WIKI.models.editors.refreshEditorsFromDisk()
await WIKI.models.editors.query().patch({ isEnabled: true }).where('key', 'markdown')
2018-05-28 18:46:55 +00:00
2018-09-01 19:15:44 +00:00
// Load loggers
await WIKI.models.loggers.refreshLoggersFromDisk()
// Load renderers
await WIKI.models.renderers.refreshRenderersFromDisk()
2018-09-01 19:15:44 +00:00
// Load search engines + enable default
await WIKI.models.searchEngines.refreshSearchEnginesFromDisk()
await WIKI.models.searchEngines.query().patch({ isEnabled: true }).where('key', 'db')
2018-06-26 02:04:47 +00:00
// Load storage targets
await WIKI.models.storage.refreshTargetsFromDisk()
2018-06-26 02:04:47 +00:00
2017-12-17 04:41:16 +00:00
// Create root administrator
WIKI.logger.info('Creating root administrator...')
await WIKI.models.users.query().delete().where({
2018-07-22 04:29:39 +00:00
providerKey: 'local',
2018-05-28 18:46:55 +00:00
email: req.body.adminEmail
})
const adminUser = await WIKI.models.users.query().insert({
2017-12-17 04:41:16 +00:00
email: req.body.adminEmail,
provider: 'local',
password: req.body.adminPassword,
2017-12-17 04:41:16 +00:00
name: 'Administrator',
2018-05-20 22:50:51 +00:00
locale: 'en',
2018-05-28 18:46:55 +00:00
defaultEditor: 'markdown',
2017-12-17 04:41:16 +00:00
tfaIsActive: false
})
await adminUser.$relatedQuery('groups').relate(adminGroup.id)
2017-12-17 04:41:16 +00:00
// Create Guest account
2018-05-28 18:46:55 +00:00
WIKI.logger.info('Creating guest account...')
await WIKI.models.users.query().delete().where({
2018-07-22 04:29:39 +00:00
providerKey: 'local',
email: 'guest@example.com'
})
const guestUser = await WIKI.models.users.query().insert({
provider: 'local',
email: 'guest@example.com',
name: 'Guest',
password: '',
locale: 'en',
defaultEditor: 'markdown',
tfaIsActive: false
})
await guestUser.$relatedQuery('groups').relate(guestGroup.id)
2018-10-22 02:25:17 +00:00
// Create site nav
WIKI.logger.info('Creating default site navigation')
await WIKI.models.navigation.query().delete().where({ key: 'site' })
await WIKI.models.navigation.query().insert({
key: 'site',
2018-11-03 05:02:08 +00:00
config: [
2018-10-22 02:25:17 +00:00
{
icon: 'home',
kind: 'link',
label: 'Home',
target: '/',
targetType: 'home'
}
2018-11-03 05:02:08 +00:00
]
2018-10-22 02:25:17 +00:00
})
WIKI.logger.info('Setup is complete!')
res.json({
ok: true,
redirectPath: '/',
redirectPort: WIKI.config.port
}).end()
2018-05-28 18:46:55 +00:00
WIKI.config.setup = false
WIKI.logger.info('Stopping Setup...')
WIKI.server.destroy(() => {
WIKI.logger.info('Setup stopped. Starting Wiki.js...')
_.delay(() => {
WIKI.kernel.bootMaster()
}, 1000)
})
} catch (err) {
res.json({ ok: false, error: err.message })
}
2017-03-25 21:03:09 +00:00
})
2017-02-26 23:06:20 +00:00
// ----------------------------------------
// Error handling
// ----------------------------------------
app.use(function (req, res, next) {
var err = new Error('Not Found')
err.status = 404
next(err)
})
app.use(function (err, req, res, next) {
res.status(err.status || 500)
res.send({
message: err.message,
error: WIKI.IS_DEBUG ? err : {}
2017-02-26 23:06:20 +00:00
})
WIKI.logger.error(err.message)
WIKI.telemetry.sendError(err)
2017-02-26 23:06:20 +00:00
})
// ----------------------------------------
// Start HTTP server
// ----------------------------------------
2018-05-28 18:46:55 +00:00
WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`)
2017-02-26 23:06:20 +00:00
app.set('port', WIKI.config.port)
WIKI.server = http.createServer(app)
2018-09-01 03:42:14 +00:00
WIKI.server.listen(WIKI.config.port, WIKI.config.bindIP)
2017-03-29 02:29:53 +00:00
var openConnections = []
WIKI.server.on('connection', (conn) => {
2017-03-29 02:29:53 +00:00
let key = conn.remoteAddress + ':' + conn.remotePort
openConnections[key] = conn
conn.on('close', () => {
delete openConnections[key]
})
})
WIKI.server.destroy = (cb) => {
WIKI.server.close(cb)
2017-03-29 02:29:53 +00:00
for (let key in openConnections) {
openConnections[key].destroy()
}
}
WIKI.server.on('error', (error) => {
2017-02-26 23:06:20 +00:00
if (error.syscall !== 'listen') {
throw error
}
switch (error.code) {
case 'EACCES':
WIKI.logger.error('Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
2017-04-05 02:04:17 +00:00
return process.exit(1)
2017-02-26 23:06:20 +00:00
case 'EADDRINUSE':
WIKI.logger.error('Port ' + WIKI.config.port + ' is already in use!')
2017-04-05 02:04:17 +00:00
return process.exit(1)
2017-02-26 23:06:20 +00:00
default:
throw error
}
})
WIKI.server.on('listening', () => {
2018-05-28 18:46:55 +00:00
WIKI.logger.info('HTTP Server: [ RUNNING ]')
WIKI.logger.info('========================================')
WIKI.logger.info(`Browse to http://localhost:${WIKI.config.port}/`)
WIKI.logger.info('========================================')
2017-02-26 23:06:20 +00:00
})
}