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.

246 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.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. var libInternalAuth = require('./libs/internalAuth')
  57. global.WSInternalKey = libInternalAuth.generateKey()
  58. // ----------------------------------------
  59. // Define Express App
  60. // ----------------------------------------
  61. global.app = express()
  62. app.use(compression())
  63. // ----------------------------------------
  64. // Security
  65. // ----------------------------------------
  66. app.use(mw.security)
  67. // ----------------------------------------
  68. // Public Assets
  69. // ----------------------------------------
  70. app.use(favicon(path.join(ROOTPATH, 'assets', 'favicon.ico')))
  71. app.use(express.static(path.join(ROOTPATH, 'assets')))
  72. // ----------------------------------------
  73. // Passport Authentication
  74. // ----------------------------------------
  75. require(CORE_PATH + 'core-libs/auth')(passport)
  76. global.rights = require(CORE_PATH + 'core-libs/rights')
  77. rights.init()
  78. var sessionStore = new SessionMongoStore({
  79. mongooseConnection: db.connection,
  80. touchAfter: 15
  81. })
  82. app.use(cookieParser())
  83. app.use(session({
  84. name: 'requarkswiki.sid',
  85. store: sessionStore,
  86. secret: appconfig.sessionSecret,
  87. resave: false,
  88. saveUninitialized: false
  89. }))
  90. app.use(flash())
  91. app.use(passport.initialize())
  92. app.use(passport.session())
  93. // ----------------------------------------
  94. // Localization Engine
  95. // ----------------------------------------
  96. lang
  97. .use(i18nextBackend)
  98. .use(i18nextMw.LanguageDetector)
  99. .init({
  100. load: 'languageOnly',
  101. ns: ['common', 'auth'],
  102. defaultNS: 'common',
  103. saveMissing: false,
  104. supportedLngs: ['en', 'fr'],
  105. preload: ['en', 'fr'],
  106. fallbackLng: 'en',
  107. backend: {
  108. loadPath: './locales/{{lng}}/{{ns}}.json'
  109. }
  110. })
  111. // ----------------------------------------
  112. // View Engine Setup
  113. // ----------------------------------------
  114. app.use(i18nextMw.handle(lang))
  115. app.set('views', path.join(ROOTPATH, 'views'))
  116. app.set('view engine', 'pug')
  117. app.use(bodyParser.json())
  118. app.use(bodyParser.urlencoded({ extended: false }))
  119. // ----------------------------------------
  120. // View accessible data
  121. // ----------------------------------------
  122. app.locals._ = require('lodash')
  123. app.locals.moment = require('moment')
  124. app.locals.appconfig = appconfig
  125. app.use(mw.flash)
  126. // ----------------------------------------
  127. // Controllers
  128. // ----------------------------------------
  129. app.use('/', ctrl.auth)
  130. app.use('/uploads', mw.auth, ctrl.uploads)
  131. app.use('/admin', mw.auth, ctrl.admin)
  132. app.use('/', mw.auth, ctrl.pages)
  133. // ----------------------------------------
  134. // Error handling
  135. // ----------------------------------------
  136. app.use(function (req, res, next) {
  137. var err = new Error('Not Found')
  138. err.status = 404
  139. next(err)
  140. })
  141. app.use(function (err, req, res, next) {
  142. res.status(err.status || 500)
  143. res.render('error', {
  144. message: err.message,
  145. error: IS_DEBUG ? err : {}
  146. })
  147. })
  148. // ----------------------------------------
  149. // Start HTTP server
  150. // ----------------------------------------
  151. winston.info('[SERVER] Starting HTTP/WS server on port ' + appconfig.port + '...')
  152. app.set('port', appconfig.port)
  153. var server = http.createServer(app)
  154. var io = socketio(server)
  155. server.listen(appconfig.port)
  156. server.on('error', (error) => {
  157. if (error.syscall !== 'listen') {
  158. throw error
  159. }
  160. // handle specific listen errors with friendly messages
  161. switch (error.code) {
  162. case 'EACCES':
  163. console.error('Listening on port ' + appconfig.port + ' requires elevated privileges!')
  164. process.exit(1)
  165. break
  166. case 'EADDRINUSE':
  167. console.error('Port ' + appconfig.port + ' is already in use!')
  168. process.exit(1)
  169. break
  170. default:
  171. throw error
  172. }
  173. })
  174. server.on('listening', () => {
  175. winston.info('[SERVER] HTTP/WS server started successfully! [RUNNING]')
  176. })
  177. // ----------------------------------------
  178. // WebSocket
  179. // ----------------------------------------
  180. io.use(passportSocketIo.authorize({
  181. key: 'requarkswiki.sid',
  182. store: sessionStore,
  183. secret: appconfig.sessionSecret,
  184. passport,
  185. cookieParser,
  186. success: (data, accept) => {
  187. accept()
  188. },
  189. fail: (data, message, error, accept) => {
  190. return accept(new Error(message))
  191. }
  192. }))
  193. io.on('connection', ctrl.ws)
  194. // ----------------------------------------
  195. // Start child processes
  196. // ----------------------------------------
  197. global.bgAgent = fork('agent.js')
  198. process.on('exit', (code) => {
  199. bgAgent.disconnect()
  200. })