master.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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(mw.auth.jwt)
  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. // ----------------------------------------
  80. // HMR (Dev Mode Only)
  81. // ----------------------------------------
  82. if (global.DEV) {
  83. app.use(global.WP_DEV.devMiddleware)
  84. app.use(global.WP_DEV.hotMiddleware)
  85. }
  86. // ----------------------------------------
  87. // Apollo Server (GraphQL)
  88. // ----------------------------------------
  89. const graphqlSchema = require('./graph')
  90. const apolloServer = new ApolloServer({
  91. ...graphqlSchema,
  92. context: ({ req, res }) => ({ req, res }),
  93. subscriptions: {
  94. onConnect: (connectionParams, webSocket) => {
  95. },
  96. path: '/graphql-subscriptions'
  97. }
  98. })
  99. apolloServer.applyMiddleware({ app })
  100. // ----------------------------------------
  101. // Routing
  102. // ----------------------------------------
  103. app.use('/', ctrl.auth)
  104. app.use('/', mw.auth.checkPath, ctrl.common)
  105. // ----------------------------------------
  106. // Error handling
  107. // ----------------------------------------
  108. app.use((req, res, next) => {
  109. var err = new Error('Not Found')
  110. err.status = 404
  111. next(err)
  112. })
  113. app.use((err, req, res, next) => {
  114. res.status(err.status || 500)
  115. res.render('error', {
  116. message: err.message,
  117. error: WIKI.IS_DEBUG ? err : {}
  118. })
  119. })
  120. // ----------------------------------------
  121. // HTTP server
  122. // ----------------------------------------
  123. let srvConnections = {}
  124. WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`)
  125. app.set('port', WIKI.config.port)
  126. WIKI.server = http.createServer(app)
  127. apolloServer.installSubscriptionHandlers(WIKI.server)
  128. WIKI.server.listen(WIKI.config.port, WIKI.config.bindIP)
  129. WIKI.server.on('error', (error) => {
  130. if (error.syscall !== 'listen') {
  131. throw error
  132. }
  133. // handle specific listen errors with friendly messages
  134. switch (error.code) {
  135. case 'EACCES':
  136. WIKI.logger.error('Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
  137. return process.exit(1)
  138. case 'EADDRINUSE':
  139. WIKI.logger.error('Port ' + WIKI.config.port + ' is already in use!')
  140. return process.exit(1)
  141. default:
  142. throw error
  143. }
  144. })
  145. WIKI.server.on('connection', conn => {
  146. let key = `${conn.remoteAddress}:${conn.remotePort}`
  147. srvConnections[key] = conn
  148. conn.on('close', function() {
  149. delete srvConnections[key]
  150. })
  151. })
  152. WIKI.server.on('listening', () => {
  153. WIKI.logger.info('HTTP Server: [ RUNNING ]')
  154. })
  155. WIKI.server.destroy = (cb) => {
  156. WIKI.server.close(cb)
  157. for (let key in srvConnections) {
  158. srvConnections[key].destroy()
  159. }
  160. }
  161. return true
  162. }