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.

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