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.

271 lines
6.9 KiB

  1. 'use strict'
  2. // ===========================================
  3. // Wiki.js
  4. // 1.0.0
  5. // Licensed under AGPLv3
  6. // ===========================================
  7. const path = require('path')
  8. const ROOTPATH = process.cwd()
  9. const SERVERPATH = path.join(ROOTPATH, 'server')
  10. global.ROOTPATH = ROOTPATH
  11. global.SERVERPATH = SERVERPATH
  12. const IS_DEBUG = process.env.NODE_ENV === 'development'
  13. process.env.VIPS_WARNING = false
  14. // if (IS_DEBUG) {
  15. // require('@glimpse/glimpse').init()
  16. // }
  17. let appconf = require('./libs/config')()
  18. global.appconfig = appconf.config
  19. global.appdata = appconf.data
  20. // ----------------------------------------
  21. // Load Winston
  22. // ----------------------------------------
  23. global.winston = require('./libs/logger')(IS_DEBUG, 'SERVER')
  24. global.winston.info('Wiki.js is initializing...')
  25. // ----------------------------------------
  26. // Load global modules
  27. // ----------------------------------------
  28. global.lcdata = require('./libs/local').init()
  29. global.db = require('./libs/db').init()
  30. global.entries = require('./libs/entries').init()
  31. global.git = require('./libs/git').init(false)
  32. global.lang = require('i18next')
  33. global.mark = require('./libs/markdown')
  34. global.search = require('./libs/search').init()
  35. global.upl = require('./libs/uploads').init()
  36. // ----------------------------------------
  37. // Load modules
  38. // ----------------------------------------
  39. const autoload = require('auto-load')
  40. const bodyParser = require('body-parser')
  41. const compression = require('compression')
  42. const cookieParser = require('cookie-parser')
  43. const express = require('express')
  44. const favicon = require('serve-favicon')
  45. const flash = require('connect-flash')
  46. const fork = require('child_process').fork
  47. const http = require('http')
  48. const i18nBackend = require('i18next-node-fs-backend')
  49. const passport = require('passport')
  50. const passportSocketIo = require('passport.socketio')
  51. const session = require('express-session')
  52. const SessionMongoStore = require('connect-mongo')(session)
  53. const graceful = require('node-graceful')
  54. const socketio = require('socket.io')
  55. var mw = autoload(path.join(SERVERPATH, '/middlewares'))
  56. var ctrl = autoload(path.join(SERVERPATH, '/controllers'))
  57. // ----------------------------------------
  58. // Define Express App
  59. // ----------------------------------------
  60. const app = express()
  61. global.app = app
  62. app.use(compression())
  63. // ----------------------------------------
  64. // Security
  65. // ----------------------------------------
  66. app.use(mw.security)
  67. // ----------------------------------------
  68. // Public Assets
  69. // ----------------------------------------
  70. app.use(favicon(path.join(ROOTPATH, 'assets', 'favicon.ico')))
  71. app.use(express.static(path.join(ROOTPATH, 'assets')))
  72. // ----------------------------------------
  73. // Passport Authentication
  74. // ----------------------------------------
  75. require('./libs/auth')(passport)
  76. global.rights = require('./libs/rights')
  77. global.rights.init()
  78. let sessionStore = new SessionMongoStore({
  79. mongooseConnection: global.db.connection,
  80. touchAfter: 15
  81. })
  82. app.use(cookieParser())
  83. app.use(session({
  84. name: 'wikijs.sid',
  85. store: sessionStore,
  86. secret: appconfig.sessionSecret,
  87. resave: false,
  88. saveUninitialized: false
  89. }))
  90. app.use(flash())
  91. app.use(passport.initialize())
  92. app.use(passport.session())
  93. // ----------------------------------------
  94. // SEO
  95. // ----------------------------------------
  96. app.use(mw.seo)
  97. // ----------------------------------------
  98. // Localization Engine
  99. // ----------------------------------------
  100. global.lang
  101. .use(i18nBackend)
  102. .init({
  103. load: 'languageOnly',
  104. ns: ['common', 'admin', 'auth', 'errors', 'git'],
  105. defaultNS: 'common',
  106. saveMissing: false,
  107. preload: [appconfig.lang],
  108. lng: appconfig.lang,
  109. fallbackLng: 'en',
  110. backend: {
  111. loadPath: path.join(SERVERPATH, 'locales/{{lng}}/{{ns}}.json')
  112. }
  113. })
  114. // ----------------------------------------
  115. // View Engine Setup
  116. // ----------------------------------------
  117. app.set('views', path.join(SERVERPATH, 'views'))
  118. app.set('view engine', 'pug')
  119. app.use(bodyParser.json({ limit: '1mb' }))
  120. app.use(bodyParser.urlencoded({ extended: false, limit: '1mb' }))
  121. // ----------------------------------------
  122. // View accessible data
  123. // ----------------------------------------
  124. app.locals._ = require('lodash')
  125. app.locals.t = global.lang.t.bind(global.lang)
  126. app.locals.moment = require('moment')
  127. app.locals.moment.locale(appconfig.lang)
  128. app.locals.appconfig = appconfig
  129. app.use(mw.flash)
  130. // ----------------------------------------
  131. // Controllers
  132. // ----------------------------------------
  133. app.use('/', ctrl.auth)
  134. app.use('/uploads', mw.auth, ctrl.uploads)
  135. app.use('/admin', mw.auth, ctrl.admin)
  136. app.use('/', mw.auth, ctrl.pages)
  137. // ----------------------------------------
  138. // Error handling
  139. // ----------------------------------------
  140. app.use(function (req, res, next) {
  141. var err = new Error('Not Found')
  142. err.status = 404
  143. next(err)
  144. })
  145. app.use(function (err, req, res, next) {
  146. res.status(err.status || 500)
  147. res.render('error', {
  148. message: err.message,
  149. error: IS_DEBUG ? err : {}
  150. })
  151. })
  152. // ----------------------------------------
  153. // Start HTTP server
  154. // ----------------------------------------
  155. global.winston.info('Starting HTTP/WS server on port ' + appconfig.port + '...')
  156. app.set('port', appconfig.port)
  157. var server = http.createServer(app)
  158. var io = socketio(server)
  159. server.listen(appconfig.port)
  160. server.on('error', (error) => {
  161. if (error.syscall !== 'listen') {
  162. throw error
  163. }
  164. // handle specific listen errors with friendly messages
  165. switch (error.code) {
  166. case 'EACCES':
  167. global.winston.error('Listening on port ' + appconfig.port + ' requires elevated privileges!')
  168. return process.exit(1)
  169. case 'EADDRINUSE':
  170. global.winston.error('Port ' + appconfig.port + ' is already in use!')
  171. return process.exit(1)
  172. default:
  173. throw error
  174. }
  175. })
  176. server.on('listening', () => {
  177. global.winston.info('HTTP/WS server started successfully! [RUNNING]')
  178. })
  179. // ----------------------------------------
  180. // WebSocket
  181. // ----------------------------------------
  182. io.use(passportSocketIo.authorize({
  183. key: 'wikijs.sid',
  184. store: sessionStore,
  185. secret: appconfig.sessionSecret,
  186. cookieParser,
  187. success: (data, accept) => {
  188. accept()
  189. },
  190. fail: (data, message, error, accept) => {
  191. accept()
  192. }
  193. }))
  194. io.on('connection', ctrl.ws)
  195. // ----------------------------------------
  196. // Start child processes
  197. // ----------------------------------------
  198. let bgAgent = fork(path.join(SERVERPATH, 'agent.js'))
  199. bgAgent.on('message', m => {
  200. if (!m.action) {
  201. return
  202. }
  203. switch (m.action) {
  204. case 'searchAdd':
  205. global.search.add(m.content)
  206. break
  207. }
  208. })
  209. // ----------------------------------------
  210. // Graceful shutdown
  211. // ----------------------------------------
  212. graceful.on('exit', () => {
  213. global.winston.info('- SHUTTING DOWN - Performing git sync...')
  214. return global.git.resync().then(() => {
  215. global.winston.info('- SHUTTING DOWN - Git sync successful. Now safe to exit.')
  216. process.kill(process.pid, 'SIGINT')
  217. })
  218. })