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.

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