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.

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