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.

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