You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

300 lines
8.4 KiB

  1. const autoload = require('auto-load')
  2. const bodyParser = require('body-parser')
  3. const compression = require('compression')
  4. const cookieParser = require('cookie-parser')
  5. const cors = require('cors')
  6. const express = require('express')
  7. const session = require('express-session')
  8. const KnexSessionStore = require('connect-session-knex')(session)
  9. const favicon = require('serve-favicon')
  10. const fs = require('fs-extra')
  11. const http = require('http')
  12. const https = require('https')
  13. const path = require('path')
  14. const _ = require('lodash')
  15. const { ApolloServer } = require('apollo-server-express')
  16. /* global WIKI */
  17. module.exports = async () => {
  18. // ----------------------------------------
  19. // Load core modules
  20. // ----------------------------------------
  21. WIKI.auth = require('./core/auth').init()
  22. WIKI.lang = require('./core/localization').init()
  23. WIKI.mail = require('./core/mail').init()
  24. WIKI.system = require('./core/system').init()
  25. // ----------------------------------------
  26. // Load middlewares
  27. // ----------------------------------------
  28. var mw = autoload(path.join(WIKI.SERVERPATH, '/middlewares'))
  29. var ctrl = autoload(path.join(WIKI.SERVERPATH, '/controllers'))
  30. // ----------------------------------------
  31. // Define Express App
  32. // ----------------------------------------
  33. const app = express()
  34. WIKI.app = app
  35. app.use(compression())
  36. // ----------------------------------------
  37. // Security
  38. // ----------------------------------------
  39. app.use(mw.security)
  40. app.use(cors(WIKI.config.cors))
  41. app.options('*', cors(WIKI.config.cors))
  42. if (WIKI.config.trustProxy) {
  43. app.enable('trust proxy')
  44. }
  45. // ----------------------------------------
  46. // Public Assets
  47. // ----------------------------------------
  48. app.use(favicon(path.join(WIKI.ROOTPATH, 'assets', 'favicon.ico')))
  49. app.use(express.static(path.join(WIKI.ROOTPATH, 'assets'), {
  50. index: false,
  51. maxAge: '7d'
  52. }))
  53. // ----------------------------------------
  54. // Passport Authentication
  55. // ----------------------------------------
  56. app.use(cookieParser())
  57. app.use(session({
  58. secret: WIKI.config.sessionSecret,
  59. resave: false,
  60. saveUninitialized: false,
  61. store: new KnexSessionStore({
  62. knex: WIKI.models.knex
  63. })
  64. }))
  65. app.use(WIKI.auth.passport.initialize())
  66. app.use(WIKI.auth.authenticate)
  67. // ----------------------------------------
  68. // SEO
  69. // ----------------------------------------
  70. app.use(mw.seo)
  71. // ----------------------------------------
  72. // View Engine Setup
  73. // ----------------------------------------
  74. app.set('views', path.join(WIKI.SERVERPATH, 'views'))
  75. app.set('view engine', 'pug')
  76. app.use(bodyParser.json({ limit: '1mb' }))
  77. app.use(bodyParser.urlencoded({ extended: false, limit: '1mb' }))
  78. // ----------------------------------------
  79. // Localization
  80. // ----------------------------------------
  81. WIKI.lang.attachMiddleware(app)
  82. // ----------------------------------------
  83. // View accessible data
  84. // ----------------------------------------
  85. app.locals.analyticsCode = {}
  86. app.locals.basedir = WIKI.ROOTPATH
  87. app.locals.config = WIKI.config
  88. app.locals.pageMeta = {
  89. title: '',
  90. description: WIKI.config.description,
  91. image: '',
  92. url: '/'
  93. }
  94. // ----------------------------------------
  95. // HMR (Dev Mode Only)
  96. // ----------------------------------------
  97. if (global.DEV) {
  98. app.use(global.WP_DEV.devMiddleware)
  99. app.use(global.WP_DEV.hotMiddleware)
  100. }
  101. // ----------------------------------------
  102. // Apollo Server (GraphQL)
  103. // ----------------------------------------
  104. const graphqlSchema = require('./graph')
  105. const apolloServer = new ApolloServer({
  106. ...graphqlSchema,
  107. context: ({ req, res }) => ({ req, res }),
  108. subscriptions: {
  109. onConnect: (connectionParams, webSocket) => {
  110. },
  111. path: '/graphql-subscriptions'
  112. }
  113. })
  114. apolloServer.applyMiddleware({ app })
  115. // ----------------------------------------
  116. // Routing
  117. // ----------------------------------------
  118. app.use(async (req, res, next) => {
  119. res.locals.siteConfig = {
  120. title: WIKI.config.title,
  121. theme: WIKI.config.theming.theme,
  122. darkMode: WIKI.config.theming.darkMode,
  123. lang: WIKI.config.lang.code,
  124. rtl: WIKI.config.lang.rtl,
  125. company: WIKI.config.company
  126. }
  127. res.locals.langs = await WIKI.models.locales.getNavLocales({ cache: true })
  128. res.locals.analyticsCode = await WIKI.models.analytics.getCode({ cache: true })
  129. next()
  130. })
  131. app.use('/', ctrl.auth)
  132. app.use('/', ctrl.upload)
  133. app.use('/', ctrl.common)
  134. // ----------------------------------------
  135. // Error handling
  136. // ----------------------------------------
  137. app.use((req, res, next) => {
  138. var err = new Error('Not Found')
  139. err.status = 404
  140. next(err)
  141. })
  142. app.use((err, req, res, next) => {
  143. res.status(err.status || 500)
  144. _.set(res.locals, 'pageMeta.title', 'Error')
  145. res.render('error', {
  146. message: err.message,
  147. error: WIKI.IS_DEBUG ? err : {}
  148. })
  149. })
  150. // ----------------------------------------
  151. // HTTP/S server
  152. // ----------------------------------------
  153. let srvConnections = {}
  154. app.set('port', WIKI.config.port)
  155. if (WIKI.config.ssl.enabled) {
  156. WIKI.logger.info(`HTTPS Server on port: [ ${WIKI.config.port} ]`)
  157. const tlsOpts = {}
  158. try {
  159. if (WIKI.config.ssl.format === 'pem') {
  160. tlsOpts.key = fs.readFileSync(WIKI.config.ssl.key)
  161. tlsOpts.cert = fs.readFileSync(WIKI.config.ssl.cert)
  162. } else {
  163. tlsOpts.pfx = fs.readFileSync(WIKI.config.ssl.pfx)
  164. }
  165. if (!_.isEmpty(WIKI.config.ssl.passphrase)) {
  166. tlsOpts.passphrase = WIKI.config.ssl.passphrase
  167. }
  168. if (!_.isEmpty(WIKI.config.ssl.dhparam)) {
  169. tlsOpts.dhparam = WIKI.config.ssl.dhparam
  170. }
  171. } catch (err) {
  172. WIKI.logger.error('Failed to setup HTTPS server parameters:')
  173. WIKI.logger.error(err)
  174. return process.exit(1)
  175. }
  176. WIKI.server = https.createServer(tlsOpts, app)
  177. // HTTP Redirect Server
  178. if (WIKI.config.ssl.redirectNonSSLPort) {
  179. WIKI.serverAlt = http.createServer((req, res) => {
  180. res.writeHead(301, { 'Location': 'https://' + req.headers['host'] + req.url })
  181. res.end()
  182. })
  183. }
  184. } else {
  185. WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`)
  186. WIKI.server = http.createServer(app)
  187. }
  188. apolloServer.installSubscriptionHandlers(WIKI.server)
  189. WIKI.server.listen(WIKI.config.port, WIKI.config.bindIP)
  190. WIKI.server.on('error', (error) => {
  191. if (error.syscall !== 'listen') {
  192. throw error
  193. }
  194. // handle specific listen errors with friendly messages
  195. switch (error.code) {
  196. case 'EACCES':
  197. WIKI.logger.error('Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
  198. return process.exit(1)
  199. case 'EADDRINUSE':
  200. WIKI.logger.error('Port ' + WIKI.config.port + ' is already in use!')
  201. return process.exit(1)
  202. default:
  203. throw error
  204. }
  205. })
  206. WIKI.server.on('connection', conn => {
  207. let key = `${conn.remoteAddress}:${conn.remotePort}`
  208. srvConnections[key] = conn
  209. conn.on('close', function() {
  210. delete srvConnections[key]
  211. })
  212. })
  213. WIKI.server.on('listening', () => {
  214. if (WIKI.config.ssl.enabled) {
  215. WIKI.logger.info('HTTPS Server: [ RUNNING ]')
  216. // Start HTTP Redirect Server
  217. if (WIKI.config.ssl.redirectNonSSLPort) {
  218. WIKI.serverAlt.listen(WIKI.config.ssl.redirectNonSSLPort, WIKI.config.bindIP)
  219. WIKI.serverAlt.on('error', (error) => {
  220. if (error.syscall !== 'listen') {
  221. throw error
  222. }
  223. switch (error.code) {
  224. case 'EACCES':
  225. WIKI.logger.error('(HTTP Redirect) Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
  226. return process.exit(1)
  227. case 'EADDRINUSE':
  228. WIKI.logger.error('(HTTP Redirect) Port ' + WIKI.config.port + ' is already in use!')
  229. return process.exit(1)
  230. default:
  231. throw error
  232. }
  233. })
  234. WIKI.serverAlt.on('listening', () => {
  235. WIKI.logger.info('HTTP Server: [ RUNNING in redirect mode ]')
  236. })
  237. }
  238. } else {
  239. WIKI.logger.info('HTTP Server: [ RUNNING ]')
  240. }
  241. })
  242. WIKI.server.destroy = (cb) => {
  243. WIKI.server.close(cb)
  244. for (let key in srvConnections) {
  245. srvConnections[key].destroy()
  246. }
  247. if (WIKI.config.ssl.enabled && WIKI.config.ssl.redirectNonSSLPort) {
  248. WIKI.serverAlt.close(cb)
  249. }
  250. }
  251. return true
  252. }