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.

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