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.

219 lines
5.8 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 session = require('express-session')
  11. const SessionRedisStore = require('connect-redis')(session)
  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. // ----------------------------------------
  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. let sessionStore = new SessionRedisStore({
  55. client: WIKI.redis
  56. })
  57. app.use(cookieParser())
  58. app.use(session({
  59. name: 'wikijs.sid',
  60. store: sessionStore,
  61. secret: WIKI.config.sessionSecret,
  62. resave: false,
  63. saveUninitialized: false
  64. }))
  65. app.use(WIKI.auth.passport.initialize())
  66. app.use(WIKI.auth.passport.session())
  67. // ----------------------------------------
  68. // SEO
  69. // ----------------------------------------
  70. app.use(mw.seo)
  71. // ----------------------------------------
  72. // View Engine Setup
  73. // ----------------------------------------
  74. app.set('views', path.join(WIKI.SERVERPATH, 'views'))
  75. app.set('view engine', 'pug')
  76. app.use(bodyParser.json({ limit: '1mb' }))
  77. app.use(bodyParser.urlencoded({ extended: false, limit: '1mb' }))
  78. // ----------------------------------------
  79. // Localization
  80. // ----------------------------------------
  81. WIKI.lang.attachMiddleware(app)
  82. // ----------------------------------------
  83. // View accessible data
  84. // ----------------------------------------
  85. app.locals.basedir = WIKI.ROOTPATH
  86. app.locals._ = require('lodash')
  87. app.locals.moment = require('moment')
  88. app.locals.moment.locale(WIKI.config.lang.code)
  89. app.locals.config = WIKI.config
  90. // ----------------------------------------
  91. // HMR (Dev Mode Only)
  92. // ----------------------------------------
  93. if (global.DEV) {
  94. app.use(global.WP_DEV.devMiddleware)
  95. app.use(global.WP_DEV.hotMiddleware)
  96. }
  97. // ----------------------------------------
  98. // Apollo Server (GraphQL)
  99. // ----------------------------------------
  100. const graphqlSchema = require('./graph')
  101. const apolloServer = new ApolloServer({
  102. ...graphqlSchema,
  103. context: ({ req, res }) => ({ req, res }),
  104. subscriptions: {
  105. onConnect: (connectionParams, webSocket) => {
  106. },
  107. path: '/graphql-subscriptions'
  108. }
  109. })
  110. apolloServer.applyMiddleware({ app })
  111. // ----------------------------------------
  112. // Routing
  113. // ----------------------------------------
  114. app.use('/', ctrl.auth)
  115. app.use('/', mw.auth, ctrl.common)
  116. // ----------------------------------------
  117. // Error handling
  118. // ----------------------------------------
  119. app.use((req, res, next) => {
  120. var err = new Error('Not Found')
  121. err.status = 404
  122. next(err)
  123. })
  124. app.use((err, req, res, next) => {
  125. res.status(err.status || 500)
  126. res.render('error', {
  127. message: err.message,
  128. error: WIKI.IS_DEBUG ? err : {}
  129. })
  130. })
  131. // ----------------------------------------
  132. // HTTP server
  133. // ----------------------------------------
  134. let srvConnections = {}
  135. WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`)
  136. app.set('port', WIKI.config.port)
  137. WIKI.server = http.createServer(app)
  138. apolloServer.installSubscriptionHandlers(WIKI.server)
  139. WIKI.server.listen(WIKI.config.port, WIKI.config.bindIP)
  140. WIKI.server.on('error', (error) => {
  141. if (error.syscall !== 'listen') {
  142. throw error
  143. }
  144. // handle specific listen errors with friendly messages
  145. switch (error.code) {
  146. case 'EACCES':
  147. WIKI.logger.error('Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
  148. return process.exit(1)
  149. case 'EADDRINUSE':
  150. WIKI.logger.error('Port ' + WIKI.config.port + ' is already in use!')
  151. return process.exit(1)
  152. default:
  153. throw error
  154. }
  155. })
  156. WIKI.server.on('connection', conn => {
  157. let key = `${conn.remoteAddress}:${conn.remotePort}`
  158. srvConnections[key] = conn
  159. conn.on('close', function() {
  160. delete srvConnections[key]
  161. })
  162. })
  163. WIKI.server.on('listening', () => {
  164. WIKI.logger.info('HTTP Server: [ RUNNING ]')
  165. })
  166. WIKI.server.destroy = (cb) => {
  167. WIKI.server.close(cb)
  168. for (let key in srvConnections) {
  169. srvConnections[key].destroy()
  170. }
  171. }
  172. return true
  173. }