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.7 KiB

  1. 'use strict'
  2. /* global wiki */
  3. const Promise = require('bluebird')
  4. wiki.redis = require('./modules/redis').init()
  5. wiki.queue = require('./modules/queue').init()
  6. module.exports = Promise.join(
  7. wiki.db.onReady,
  8. wiki.configSvc.loadFromDb(),
  9. wiki.queue.clean()
  10. ).then(() => {
  11. // ----------------------------------------
  12. // Load global modules
  13. // ----------------------------------------
  14. wiki.auth = require('./modules/auth').init()
  15. wiki.disk = require('./modules/disk').init()
  16. wiki.docs = require('./modules/documents').init()
  17. wiki.git = require('./modules/git').init(false)
  18. wiki.lang = require('i18next')
  19. wiki.mark = require('./modules/markdown')
  20. wiki.search = require('./modules/search').init()
  21. wiki.upl = require('./modules/uploads').init()
  22. // ----------------------------------------
  23. // Load modules
  24. // ----------------------------------------
  25. const autoload = require('auto-load')
  26. const bodyParser = require('body-parser')
  27. const compression = require('compression')
  28. const cookieParser = require('cookie-parser')
  29. const express = require('express')
  30. const favicon = require('serve-favicon')
  31. const flash = require('connect-flash')
  32. const http = require('http')
  33. const i18nBackend = require('i18next-node-fs-backend')
  34. const path = require('path')
  35. const passportSocketIo = require('passport.socketio')
  36. const session = require('express-session')
  37. const SessionRedisStore = require('connect-redis')(session)
  38. const graceful = require('node-graceful')
  39. const socketio = require('socket.io')
  40. const graphqlApollo = require('apollo-server-express')
  41. const graphqlSchema = require('./modules/graphql')
  42. var mw = autoload(path.join(wiki.SERVERPATH, '/middlewares'))
  43. var ctrl = autoload(path.join(wiki.SERVERPATH, '/controllers'))
  44. // ----------------------------------------
  45. // Define Express App
  46. // ----------------------------------------
  47. const app = express()
  48. wiki.app = app
  49. app.use(compression())
  50. // ----------------------------------------
  51. // Security
  52. // ----------------------------------------
  53. app.use(mw.security)
  54. // ----------------------------------------
  55. // Public Assets
  56. // ----------------------------------------
  57. app.use(favicon(path.join(wiki.ROOTPATH, 'assets', 'favicon.ico')))
  58. app.use(express.static(path.join(wiki.ROOTPATH, 'assets'), {
  59. index: false,
  60. maxAge: '7d'
  61. }))
  62. // ----------------------------------------
  63. // Passport Authentication
  64. // ----------------------------------------
  65. let sessionStore = new SessionRedisStore({
  66. client: wiki.redis
  67. })
  68. app.use(cookieParser())
  69. app.use(session({
  70. name: 'wikijs.sid',
  71. store: sessionStore,
  72. secret: wiki.config.site.sessionSecret,
  73. resave: false,
  74. saveUninitialized: false
  75. }))
  76. app.use(flash())
  77. app.use(wiki.auth.passport.initialize())
  78. app.use(wiki.auth.passport.session())
  79. // ----------------------------------------
  80. // SEO
  81. // ----------------------------------------
  82. app.use(mw.seo)
  83. // ----------------------------------------
  84. // Localization Engine
  85. // ----------------------------------------
  86. wiki.lang.use(i18nBackend).init({
  87. load: 'languageOnly',
  88. ns: ['common', 'admin', 'auth', 'errors', 'git'],
  89. defaultNS: 'common',
  90. saveMissing: false,
  91. preload: [wiki.config.site.lang],
  92. lng: wiki.config.site.lang,
  93. fallbackLng: 'en',
  94. backend: {
  95. loadPath: path.join(wiki.SERVERPATH, 'locales/{{lng}}/{{ns}}.json')
  96. }
  97. })
  98. // ----------------------------------------
  99. // View Engine Setup
  100. // ----------------------------------------
  101. app.set('views', path.join(wiki.SERVERPATH, 'views'))
  102. app.set('view engine', 'pug')
  103. app.use(bodyParser.json({ limit: '1mb' }))
  104. app.use(bodyParser.urlencoded({ extended: false, limit: '1mb' }))
  105. // ----------------------------------------
  106. // View accessible data
  107. // ----------------------------------------
  108. app.locals.basedir = wiki.ROOTPATH
  109. app.locals._ = require('lodash')
  110. app.locals.t = wiki.lang.t.bind(wiki.lang)
  111. app.locals.moment = require('moment')
  112. app.locals.moment.locale(wiki.config.site.lang)
  113. app.locals.config = wiki.config
  114. app.use(mw.flash)
  115. // ----------------------------------------
  116. // Controllers
  117. // ----------------------------------------
  118. app.use('/', ctrl.auth)
  119. app.use('/graphql', graphqlApollo.graphqlExpress({ schema: graphqlSchema }))
  120. app.use('/graphiql', graphqlApollo.graphiqlExpress({ endpointURL: '/graphql' }))
  121. // app.use('/uploads', mw.auth, ctrl.uploads)
  122. app.use('/admin', mw.auth, ctrl.admin)
  123. app.use('/', mw.auth, ctrl.pages)
  124. // ----------------------------------------
  125. // Error handling
  126. // ----------------------------------------
  127. app.use(function (req, res, next) {
  128. var err = new Error('Not Found')
  129. err.status = 404
  130. next(err)
  131. })
  132. app.use(function (err, req, res, next) {
  133. res.status(err.status || 500)
  134. res.render('error', {
  135. message: err.message,
  136. error: wiki.IS_DEBUG ? err : {}
  137. })
  138. })
  139. // ----------------------------------------
  140. // Start HTTP server
  141. // ----------------------------------------
  142. wiki.logger.info(`HTTP/WS Server on port: ${wiki.config.port}`)
  143. app.set('port', wiki.config.port)
  144. var server = http.createServer(app)
  145. var io = socketio(server)
  146. server.listen(wiki.config.port)
  147. server.on('error', (error) => {
  148. if (error.syscall !== 'listen') {
  149. throw error
  150. }
  151. // handle specific listen errors with friendly messages
  152. switch (error.code) {
  153. case 'EACCES':
  154. wiki.logger.error('Listening on port ' + wiki.config.port + ' requires elevated privileges!')
  155. return process.exit(1)
  156. case 'EADDRINUSE':
  157. wiki.logger.error('Port ' + wiki.config.port + ' is already in use!')
  158. return process.exit(1)
  159. default:
  160. throw error
  161. }
  162. })
  163. server.on('listening', () => {
  164. wiki.logger.info('HTTP/WS Server: RUNNING')
  165. })
  166. // ----------------------------------------
  167. // WebSocket
  168. // ----------------------------------------
  169. io.use(passportSocketIo.authorize({
  170. key: 'wikijs.sid',
  171. store: sessionStore,
  172. secret: wiki.config.site.sessionSecret,
  173. cookieParser,
  174. success: (data, accept) => {
  175. accept()
  176. },
  177. fail: (data, message, error, accept) => {
  178. accept()
  179. }
  180. }))
  181. io.on('connection', ctrl.ws)
  182. // ----------------------------------------
  183. // Graceful shutdown
  184. // ----------------------------------------
  185. graceful.on('exit', () => {
  186. // wiki.logger.info('- SHUTTING DOWN - Terminating Background Agent...')
  187. // bgAgent.kill()
  188. wiki.logger.info('- SHUTTING DOWN - Performing git sync...')
  189. return global.git.resync().then(() => {
  190. wiki.logger.info('- SHUTTING DOWN - Git sync successful. Now safe to exit.')
  191. process.exit()
  192. })
  193. })
  194. return true
  195. }).catch(err => {
  196. wiki.logger.error(err)
  197. process.exit(1)
  198. })