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.

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