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.

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