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.

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