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.

213 lines
5.6 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 favicon = require('serve-favicon')
  8. const http = require('http')
  9. const path = require('path')
  10. const { ApolloServer } = require('apollo-server-express')
  11. // const oauth2orize = require('oauth2orize')
  12. /* global WIKI */
  13. module.exports = async () => {
  14. // ----------------------------------------
  15. // Load core modules
  16. // ----------------------------------------
  17. WIKI.auth = require('./core/auth').init()
  18. WIKI.lang = require('./core/localization').init()
  19. WIKI.mail = require('./core/mail').init()
  20. // ----------------------------------------
  21. // Load middlewares
  22. // ----------------------------------------
  23. var mw = autoload(path.join(WIKI.SERVERPATH, '/middlewares'))
  24. var ctrl = autoload(path.join(WIKI.SERVERPATH, '/controllers'))
  25. // ----------------------------------------
  26. // Define Express App
  27. // ----------------------------------------
  28. const app = express()
  29. WIKI.app = app
  30. app.use(compression())
  31. // ----------------------------------------
  32. // Security
  33. // ----------------------------------------
  34. app.use(mw.security)
  35. app.use(cors(WIKI.config.cors))
  36. app.options('*', cors(WIKI.config.cors))
  37. app.enable('trust proxy')
  38. // ----------------------------------------
  39. // Public Assets
  40. // ----------------------------------------
  41. app.use(favicon(path.join(WIKI.ROOTPATH, 'assets', 'favicon.ico')))
  42. app.use(express.static(path.join(WIKI.ROOTPATH, 'assets'), {
  43. index: false,
  44. maxAge: '7d'
  45. }))
  46. // ----------------------------------------
  47. // OAuth2 Server
  48. // ----------------------------------------
  49. // const OAuth2Server = oauth2orize.createServer()
  50. // ----------------------------------------
  51. // Passport Authentication
  52. // ----------------------------------------
  53. app.use(cookieParser())
  54. app.use(WIKI.auth.passport.initialize())
  55. app.use(WIKI.auth.authenticate)
  56. // ----------------------------------------
  57. // SEO
  58. // ----------------------------------------
  59. app.use(mw.seo)
  60. // ----------------------------------------
  61. // View Engine Setup
  62. // ----------------------------------------
  63. app.set('views', path.join(WIKI.SERVERPATH, 'views'))
  64. app.set('view engine', 'pug')
  65. app.use(bodyParser.json({ limit: '1mb' }))
  66. app.use(bodyParser.urlencoded({ extended: false, limit: '1mb' }))
  67. // ----------------------------------------
  68. // Localization
  69. // ----------------------------------------
  70. WIKI.lang.attachMiddleware(app)
  71. // ----------------------------------------
  72. // View accessible data
  73. // ----------------------------------------
  74. app.locals.basedir = WIKI.ROOTPATH
  75. app.locals._ = require('lodash')
  76. app.locals.moment = require('moment')
  77. app.locals.moment.locale(WIKI.config.lang.code)
  78. app.locals.config = WIKI.config
  79. app.locals.pageMeta = {
  80. title: '',
  81. description: WIKI.config.description,
  82. image: '',
  83. url: '/'
  84. }
  85. // ----------------------------------------
  86. // HMR (Dev Mode Only)
  87. // ----------------------------------------
  88. if (global.DEV) {
  89. app.use(global.WP_DEV.devMiddleware)
  90. app.use(global.WP_DEV.hotMiddleware)
  91. }
  92. // ----------------------------------------
  93. // Apollo Server (GraphQL)
  94. // ----------------------------------------
  95. const graphqlSchema = require('./graph')
  96. const apolloServer = new ApolloServer({
  97. ...graphqlSchema,
  98. context: ({ req, res }) => ({ req, res }),
  99. subscriptions: {
  100. onConnect: (connectionParams, webSocket) => {
  101. },
  102. path: '/graphql-subscriptions'
  103. }
  104. })
  105. apolloServer.applyMiddleware({ app })
  106. // ----------------------------------------
  107. // Routing
  108. // ----------------------------------------
  109. app.use('/', ctrl.auth)
  110. app.use('/', ctrl.common)
  111. // ----------------------------------------
  112. // Error handling
  113. // ----------------------------------------
  114. app.use((req, res, next) => {
  115. var err = new Error('Not Found')
  116. err.status = 404
  117. next(err)
  118. })
  119. app.use((err, req, res, next) => {
  120. res.status(err.status || 500)
  121. res.locals.pageMeta.title = 'Error'
  122. res.render('error', {
  123. message: err.message,
  124. error: WIKI.IS_DEBUG ? err : {}
  125. })
  126. })
  127. // ----------------------------------------
  128. // HTTP server
  129. // ----------------------------------------
  130. let srvConnections = {}
  131. WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`)
  132. app.set('port', WIKI.config.port)
  133. WIKI.server = http.createServer(app)
  134. apolloServer.installSubscriptionHandlers(WIKI.server)
  135. WIKI.server.listen(WIKI.config.port, WIKI.config.bindIP)
  136. WIKI.server.on('error', (error) => {
  137. if (error.syscall !== 'listen') {
  138. throw error
  139. }
  140. // handle specific listen errors with friendly messages
  141. switch (error.code) {
  142. case 'EACCES':
  143. WIKI.logger.error('Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
  144. return process.exit(1)
  145. case 'EADDRINUSE':
  146. WIKI.logger.error('Port ' + WIKI.config.port + ' is already in use!')
  147. return process.exit(1)
  148. default:
  149. throw error
  150. }
  151. })
  152. WIKI.server.on('connection', conn => {
  153. let key = `${conn.remoteAddress}:${conn.remotePort}`
  154. srvConnections[key] = conn
  155. conn.on('close', function() {
  156. delete srvConnections[key]
  157. })
  158. })
  159. WIKI.server.on('listening', () => {
  160. WIKI.logger.info('HTTP Server: [ RUNNING ]')
  161. })
  162. WIKI.server.destroy = (cb) => {
  163. WIKI.server.close(cb)
  164. for (let key in srvConnections) {
  165. srvConnections[key].destroy()
  166. }
  167. }
  168. return true
  169. }