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.

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