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.

260 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. 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. // SEO
  92. // ----------------------------------------
  93. app.use(mw.seo)
  94. // ----------------------------------------
  95. // Localization Engine
  96. // ----------------------------------------
  97. lang
  98. .use(i18nextBackend)
  99. .use(i18nextMw.LanguageDetector)
  100. .init({
  101. load: 'languageOnly',
  102. ns: ['common', 'auth'],
  103. defaultNS: 'common',
  104. saveMissing: false,
  105. supportedLngs: ['en', 'fr'],
  106. preload: ['en', 'fr'],
  107. fallbackLng: 'en',
  108. backend: {
  109. loadPath: './locales/{{lng}}/{{ns}}.json'
  110. }
  111. })
  112. // ----------------------------------------
  113. // View Engine Setup
  114. // ----------------------------------------
  115. app.use(i18nextMw.handle(lang))
  116. app.set('views', path.join(ROOTPATH, 'views'))
  117. app.set('view engine', 'pug')
  118. app.use(bodyParser.json())
  119. app.use(bodyParser.urlencoded({ extended: false }))
  120. // ----------------------------------------
  121. // View accessible data
  122. // ----------------------------------------
  123. app.locals._ = require('lodash')
  124. app.locals.moment = require('moment')
  125. app.locals.appconfig = appconfig
  126. app.use(mw.flash)
  127. // ----------------------------------------
  128. // Controllers
  129. // ----------------------------------------
  130. app.use('/', ctrl.auth)
  131. app.use('/uploads', mw.auth, ctrl.uploads)
  132. app.use('/admin', mw.auth, ctrl.admin)
  133. app.use('/', mw.auth, ctrl.pages)
  134. // ----------------------------------------
  135. // Error handling
  136. // ----------------------------------------
  137. app.use(function (req, res, next) {
  138. var err = new Error('Not Found')
  139. err.status = 404
  140. next(err)
  141. })
  142. app.use(function (err, req, res, next) {
  143. res.status(err.status || 500)
  144. res.render('error', {
  145. message: err.message,
  146. error: IS_DEBUG ? err : {}
  147. })
  148. })
  149. // ----------------------------------------
  150. // Start HTTP server
  151. // ----------------------------------------
  152. winston.info('[SERVER] Starting HTTP/WS server on port ' + appconfig.port + '...')
  153. app.set('port', appconfig.port)
  154. var server = http.createServer(app)
  155. var io = socketio(server)
  156. server.listen(appconfig.port)
  157. server.on('error', (error) => {
  158. if (error.syscall !== 'listen') {
  159. throw error
  160. }
  161. // handle specific listen errors with friendly messages
  162. switch (error.code) {
  163. case 'EACCES':
  164. console.error('Listening on port ' + appconfig.port + ' requires elevated privileges!')
  165. return process.exit(1)
  166. case 'EADDRINUSE':
  167. console.error('Port ' + appconfig.port + ' is already in use!')
  168. return process.exit(1)
  169. default:
  170. throw error
  171. }
  172. })
  173. server.on('listening', () => {
  174. winston.info('[SERVER] HTTP/WS server started successfully! [RUNNING]')
  175. })
  176. // ----------------------------------------
  177. // WebSocket
  178. // ----------------------------------------
  179. io.use(passportSocketIo.authorize({
  180. key: 'requarkswiki.sid',
  181. store: sessionStore,
  182. secret: appconfig.sessionSecret,
  183. passport,
  184. cookieParser,
  185. success: (data, accept) => {
  186. accept()
  187. },
  188. fail: (data, message, error, accept) => {
  189. return accept(new Error(message))
  190. }
  191. }))
  192. io.on('connection', ctrl.ws)
  193. // ----------------------------------------
  194. // Start child processes
  195. // ----------------------------------------
  196. let bgAgent = fork('agent.js')
  197. bgAgent.on('message', m => {
  198. if (!m.action) {
  199. return
  200. }
  201. switch (m.action) {
  202. case 'searchAdd':
  203. search.add(m.content)
  204. break
  205. }
  206. })
  207. process.on('exit', (code) => {
  208. bgAgent.disconnect()
  209. })