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.

298 lines
8.3 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.basedir = WIKI.ROOTPATH
  86. app.locals.config = WIKI.config
  87. app.locals.pageMeta = {
  88. title: '',
  89. description: WIKI.config.description,
  90. image: '',
  91. url: '/'
  92. }
  93. // ----------------------------------------
  94. // HMR (Dev Mode Only)
  95. // ----------------------------------------
  96. if (global.DEV) {
  97. app.use(global.WP_DEV.devMiddleware)
  98. app.use(global.WP_DEV.hotMiddleware)
  99. }
  100. // ----------------------------------------
  101. // Apollo Server (GraphQL)
  102. // ----------------------------------------
  103. const graphqlSchema = require('./graph')
  104. const apolloServer = new ApolloServer({
  105. ...graphqlSchema,
  106. context: ({ req, res }) => ({ req, res }),
  107. subscriptions: {
  108. onConnect: (connectionParams, webSocket) => {
  109. },
  110. path: '/graphql-subscriptions'
  111. }
  112. })
  113. apolloServer.applyMiddleware({ app })
  114. // ----------------------------------------
  115. // Routing
  116. // ----------------------------------------
  117. app.use(async (req, res, next) => {
  118. res.locals.siteConfig = {
  119. title: WIKI.config.title,
  120. theme: WIKI.config.theming.theme,
  121. darkMode: WIKI.config.theming.darkMode,
  122. lang: WIKI.config.lang.code,
  123. rtl: WIKI.config.lang.rtl,
  124. company: WIKI.config.company
  125. }
  126. res.locals.langs = await WIKI.models.locales.getNavLocales({ cache: true })
  127. next()
  128. })
  129. app.use('/', ctrl.auth)
  130. app.use('/', ctrl.upload)
  131. app.use('/', ctrl.common)
  132. // ----------------------------------------
  133. // Error handling
  134. // ----------------------------------------
  135. app.use((req, res, next) => {
  136. var err = new Error('Not Found')
  137. err.status = 404
  138. next(err)
  139. })
  140. app.use((err, req, res, next) => {
  141. res.status(err.status || 500)
  142. _.set(res.locals, 'pageMeta.title', 'Error')
  143. res.render('error', {
  144. message: err.message,
  145. error: WIKI.IS_DEBUG ? err : {}
  146. })
  147. })
  148. // ----------------------------------------
  149. // HTTP/S server
  150. // ----------------------------------------
  151. let srvConnections = {}
  152. app.set('port', WIKI.config.port)
  153. if (WIKI.config.ssl.enabled) {
  154. WIKI.logger.info(`HTTPS Server on port: [ ${WIKI.config.port} ]`)
  155. const tlsOpts = {}
  156. try {
  157. if (WIKI.config.ssl.format === 'pem') {
  158. tlsOpts.key = fs.readFileSync(WIKI.config.ssl.key)
  159. tlsOpts.cert = fs.readFileSync(WIKI.config.ssl.cert)
  160. } else {
  161. tlsOpts.pfx = fs.readFileSync(WIKI.config.ssl.pfx)
  162. }
  163. if (!_.isEmpty(WIKI.config.ssl.passphrase)) {
  164. tlsOpts.passphrase = WIKI.config.ssl.passphrase
  165. }
  166. if (!_.isEmpty(WIKI.config.ssl.dhparam)) {
  167. tlsOpts.dhparam = WIKI.config.ssl.dhparam
  168. }
  169. } catch (err) {
  170. WIKI.logger.error('Failed to setup HTTPS server parameters:')
  171. WIKI.logger.error(err)
  172. return process.exit(1)
  173. }
  174. WIKI.server = https.createServer(tlsOpts, app)
  175. // HTTP Redirect Server
  176. if (WIKI.config.ssl.redirectNonSSLPort) {
  177. WIKI.serverAlt = http.createServer((req, res) => {
  178. res.writeHead(301, { 'Location': 'https://' + req.headers['host'] + req.url })
  179. res.end()
  180. })
  181. }
  182. } else {
  183. WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`)
  184. WIKI.server = http.createServer(app)
  185. }
  186. apolloServer.installSubscriptionHandlers(WIKI.server)
  187. WIKI.server.listen(WIKI.config.port, WIKI.config.bindIP)
  188. WIKI.server.on('error', (error) => {
  189. if (error.syscall !== 'listen') {
  190. throw error
  191. }
  192. // handle specific listen errors with friendly messages
  193. switch (error.code) {
  194. case 'EACCES':
  195. WIKI.logger.error('Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
  196. return process.exit(1)
  197. case 'EADDRINUSE':
  198. WIKI.logger.error('Port ' + WIKI.config.port + ' is already in use!')
  199. return process.exit(1)
  200. default:
  201. throw error
  202. }
  203. })
  204. WIKI.server.on('connection', conn => {
  205. let key = `${conn.remoteAddress}:${conn.remotePort}`
  206. srvConnections[key] = conn
  207. conn.on('close', function() {
  208. delete srvConnections[key]
  209. })
  210. })
  211. WIKI.server.on('listening', () => {
  212. if (WIKI.config.ssl.enabled) {
  213. WIKI.logger.info('HTTPS Server: [ RUNNING ]')
  214. // Start HTTP Redirect Server
  215. if (WIKI.config.ssl.redirectNonSSLPort) {
  216. WIKI.serverAlt.listen(WIKI.config.ssl.redirectNonSSLPort, WIKI.config.bindIP)
  217. WIKI.serverAlt.on('error', (error) => {
  218. if (error.syscall !== 'listen') {
  219. throw error
  220. }
  221. switch (error.code) {
  222. case 'EACCES':
  223. WIKI.logger.error('(HTTP Redirect) Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
  224. return process.exit(1)
  225. case 'EADDRINUSE':
  226. WIKI.logger.error('(HTTP Redirect) Port ' + WIKI.config.port + ' is already in use!')
  227. return process.exit(1)
  228. default:
  229. throw error
  230. }
  231. })
  232. WIKI.serverAlt.on('listening', () => {
  233. WIKI.logger.info('HTTP Server: [ RUNNING in redirect mode ]')
  234. })
  235. }
  236. } else {
  237. WIKI.logger.info('HTTP Server: [ RUNNING ]')
  238. }
  239. })
  240. WIKI.server.destroy = (cb) => {
  241. WIKI.server.close(cb)
  242. for (let key in srvConnections) {
  243. srvConnections[key].destroy()
  244. }
  245. if (WIKI.config.ssl.enabled && WIKI.config.ssl.redirectNonSSLPort) {
  246. WIKI.serverAlt.close(cb)
  247. }
  248. }
  249. return true
  250. }