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.

259 lines
6.6 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. var libInternalAuth = require('./libs/internalAuth')
  58. global.WSInternalKey = libInternalAuth.generateKey()
  59. // ----------------------------------------
  60. // Define Express App
  61. // ----------------------------------------
  62. global.app = express()
  63. app.use(compression())
  64. // ----------------------------------------
  65. // Security
  66. // ----------------------------------------
  67. app.use(mw.security)
  68. // ----------------------------------------
  69. // Public Assets
  70. // ----------------------------------------
  71. app.use(favicon(path.join(ROOTPATH, 'assets', 'favicon.ico')))
  72. app.use(express.static(path.join(ROOTPATH, 'assets')))
  73. // ----------------------------------------
  74. // Passport Authentication
  75. // ----------------------------------------
  76. require(CORE_PATH + 'core-libs/auth')(passport)
  77. global.rights = require(CORE_PATH + 'core-libs/rights')
  78. rights.init()
  79. var sessionStore = new SessionMongoStore({
  80. mongooseConnection: db.connection,
  81. touchAfter: 15
  82. })
  83. app.use(cookieParser())
  84. app.use(session({
  85. name: 'requarkswiki.sid',
  86. store: sessionStore,
  87. secret: appconfig.sessionSecret,
  88. resave: false,
  89. saveUninitialized: false
  90. }))
  91. app.use(flash())
  92. app.use(passport.initialize())
  93. app.use(passport.session())
  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. process.exit(1)
  166. break
  167. case 'EADDRINUSE':
  168. console.error('Port ' + appconfig.port + ' is already in use!')
  169. process.exit(1)
  170. break
  171. default:
  172. throw error
  173. }
  174. })
  175. server.on('listening', () => {
  176. winston.info('[SERVER] HTTP/WS server started successfully! [RUNNING]')
  177. })
  178. // ----------------------------------------
  179. // WebSocket
  180. // ----------------------------------------
  181. io.use(passportSocketIo.authorize({
  182. key: 'requarkswiki.sid',
  183. store: sessionStore,
  184. secret: appconfig.sessionSecret,
  185. passport,
  186. cookieParser,
  187. success: (data, accept) => {
  188. accept()
  189. },
  190. fail: (data, message, error, accept) => {
  191. return accept(new Error(message))
  192. }
  193. }))
  194. io.on('connection', ctrl.ws)
  195. // ----------------------------------------
  196. // Start child processes
  197. // ----------------------------------------
  198. let bgAgent = fork('agent.js')
  199. bgAgent.on('message', m => {
  200. if (!m.action) {
  201. return
  202. }
  203. switch (m.action) {
  204. case 'searchAdd':
  205. search.add(m.content)
  206. break
  207. }
  208. })
  209. process.on('exit', (code) => {
  210. bgAgent.disconnect()
  211. })