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.

254 lines
6.3 KiB

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