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.

262 lines
6.6 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 socketio = require('socket.io')
  54. var mw = autoload(path.join(SERVERPATH, '/middlewares'))
  55. var ctrl = autoload(path.join(SERVERPATH, '/controllers'))
  56. // ----------------------------------------
  57. // Define Express App
  58. // ----------------------------------------
  59. const app = express()
  60. global.app = app
  61. app.use(compression())
  62. // ----------------------------------------
  63. // Security
  64. // ----------------------------------------
  65. app.use(mw.security)
  66. // ----------------------------------------
  67. // Public Assets
  68. // ----------------------------------------
  69. app.use(favicon(path.join(ROOTPATH, 'assets', 'favicon.ico')))
  70. app.use(express.static(path.join(ROOTPATH, 'assets')))
  71. // ----------------------------------------
  72. // Passport Authentication
  73. // ----------------------------------------
  74. require('./libs/auth')(passport)
  75. global.rights = require('./libs/rights')
  76. global.rights.init()
  77. let sessionStore = new SessionMongoStore({
  78. mongooseConnection: global.db.connection,
  79. touchAfter: 15
  80. })
  81. app.use(cookieParser())
  82. app.use(session({
  83. name: 'wikijs.sid',
  84. store: sessionStore,
  85. secret: appconfig.sessionSecret,
  86. resave: false,
  87. saveUninitialized: false
  88. }))
  89. app.use(flash())
  90. app.use(passport.initialize())
  91. app.use(passport.session())
  92. // ----------------------------------------
  93. // SEO
  94. // ----------------------------------------
  95. app.use(mw.seo)
  96. // ----------------------------------------
  97. // Localization Engine
  98. // ----------------------------------------
  99. global.lang
  100. .use(i18nBackend)
  101. .init({
  102. load: 'languageOnly',
  103. ns: ['common', 'admin', 'auth', 'errors', 'git'],
  104. defaultNS: 'common',
  105. saveMissing: false,
  106. preload: [appconfig.lang],
  107. lng: appconfig.lang,
  108. fallbackLng: 'en',
  109. backend: {
  110. loadPath: path.join(SERVERPATH, 'locales/{{lng}}/{{ns}}.json')
  111. }
  112. })
  113. // ----------------------------------------
  114. // View Engine Setup
  115. // ----------------------------------------
  116. app.set('views', path.join(SERVERPATH, 'views'))
  117. app.set('view engine', 'pug')
  118. app.use(bodyParser.json({ limit: '1mb' }))
  119. app.use(bodyParser.urlencoded({ extended: false, limit: '1mb' }))
  120. // ----------------------------------------
  121. // View accessible data
  122. // ----------------------------------------
  123. app.locals._ = require('lodash')
  124. app.locals.t = global.lang.t.bind(global.lang)
  125. app.locals.moment = require('moment')
  126. app.locals.moment.locale(appconfig.lang)
  127. app.locals.appconfig = appconfig
  128. app.use(mw.flash)
  129. // ----------------------------------------
  130. // Controllers
  131. // ----------------------------------------
  132. app.use('/', ctrl.auth)
  133. app.use('/uploads', mw.auth, ctrl.uploads)
  134. app.use('/admin', mw.auth, ctrl.admin)
  135. app.use('/', mw.auth, ctrl.pages)
  136. // ----------------------------------------
  137. // Error handling
  138. // ----------------------------------------
  139. app.use(function (req, res, next) {
  140. var err = new Error('Not Found')
  141. err.status = 404
  142. next(err)
  143. })
  144. app.use(function (err, req, res, next) {
  145. res.status(err.status || 500)
  146. res.render('error', {
  147. message: err.message,
  148. error: IS_DEBUG ? err : {}
  149. })
  150. })
  151. // ----------------------------------------
  152. // Start HTTP server
  153. // ----------------------------------------
  154. global.winston.info('Starting HTTP/WS server on port ' + appconfig.port + '...')
  155. app.set('port', appconfig.port)
  156. var server = http.createServer(app)
  157. var io = socketio(server)
  158. server.listen(appconfig.port)
  159. server.on('error', (error) => {
  160. if (error.syscall !== 'listen') {
  161. throw error
  162. }
  163. // handle specific listen errors with friendly messages
  164. switch (error.code) {
  165. case 'EACCES':
  166. global.winston.error('Listening on port ' + appconfig.port + ' requires elevated privileges!')
  167. return process.exit(1)
  168. case 'EADDRINUSE':
  169. global.winston.error('Port ' + appconfig.port + ' is already in use!')
  170. return process.exit(1)
  171. default:
  172. throw error
  173. }
  174. })
  175. server.on('listening', () => {
  176. global.winston.info('HTTP/WS server started successfully! [RUNNING]')
  177. })
  178. // ----------------------------------------
  179. // WebSocket
  180. // ----------------------------------------
  181. io.use(passportSocketIo.authorize({
  182. key: 'wikijs.sid',
  183. store: sessionStore,
  184. secret: appconfig.sessionSecret,
  185. cookieParser,
  186. success: (data, accept) => {
  187. accept()
  188. },
  189. fail: (data, message, error, accept) => {
  190. accept()
  191. }
  192. }))
  193. io.on('connection', ctrl.ws)
  194. // ----------------------------------------
  195. // Start child processes
  196. // ----------------------------------------
  197. let bgAgent = fork(path.join(SERVERPATH, 'agent.js'))
  198. bgAgent.on('message', m => {
  199. if (!m.action) {
  200. return
  201. }
  202. switch (m.action) {
  203. case 'searchAdd':
  204. global.search.add(m.content)
  205. break
  206. }
  207. })
  208. process.on('exit', (code) => {
  209. bgAgent.disconnect()
  210. })