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.4 KiB

8 years ago
  1. 'use strict'
  2. // ===========================================
  3. // Wiki.js
  4. // 1.0.0
  5. // Licensed under AGPLv3
  6. // ===========================================
  7. const path = require('path')
  8. const ROOTPATH = process.cwd()
  9. const SERVERPATH = path.join(ROOTPATH, 'server')
  10. global.ROOTPATH = ROOTPATH
  11. global.SERVERPATH = SERVERPATH
  12. const IS_DEBUG = process.env.NODE_ENV === 'development'
  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, 'SERVER')
  21. winston.info('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 session = require('express-session')
  50. const SessionMongoStore = require('connect-mongo')(session)
  51. const socketio = require('socket.io')
  52. var mw = autoload(path.join(SERVERPATH, '/middlewares'))
  53. var ctrl = autoload(path.join(SERVERPATH, '/controllers'))
  54. // ----------------------------------------
  55. // Define Express App
  56. // ----------------------------------------
  57. global.app = express()
  58. app.use(compression())
  59. // ----------------------------------------
  60. // Security
  61. // ----------------------------------------
  62. app.use(mw.security)
  63. // ----------------------------------------
  64. // Public Assets
  65. // ----------------------------------------
  66. app.use(favicon(path.join(ROOTPATH, 'assets', 'favicon.ico')))
  67. app.use(express.static(path.join(ROOTPATH, 'assets')))
  68. // ----------------------------------------
  69. // Passport Authentication
  70. // ----------------------------------------
  71. require('./libs/auth')(passport)
  72. global.rights = require('./libs/rights')
  73. rights.init()
  74. var sessionStore = new SessionMongoStore({
  75. mongooseConnection: db.connection,
  76. touchAfter: 15
  77. })
  78. app.use(cookieParser())
  79. app.use(session({
  80. name: 'requarkswiki.sid',
  81. store: sessionStore,
  82. secret: appconfig.sessionSecret,
  83. resave: false,
  84. saveUninitialized: false
  85. }))
  86. app.use(flash())
  87. app.use(passport.initialize())
  88. app.use(passport.session())
  89. // ----------------------------------------
  90. // SEO
  91. // ----------------------------------------
  92. app.use(mw.seo)
  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(SERVERPATH, '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('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. winston.error('Listening on port ' + appconfig.port + ' requires elevated privileges!')
  164. return process.exit(1)
  165. case 'EADDRINUSE':
  166. winston.error('Port ' + appconfig.port + ' is already in use!')
  167. return process.exit(1)
  168. default:
  169. throw error
  170. }
  171. })
  172. server.on('listening', () => {
  173. winston.info('HTTP/WS server started successfully! [RUNNING]')
  174. })
  175. // ----------------------------------------
  176. // WebSocket
  177. // ----------------------------------------
  178. io.use(passportSocketIo.authorize({
  179. key: 'requarkswiki.sid',
  180. store: sessionStore,
  181. secret: appconfig.sessionSecret,
  182. passport,
  183. cookieParser,
  184. success: (data, accept) => {
  185. accept()
  186. },
  187. fail: (data, message, error, accept) => {
  188. return accept(new Error(message))
  189. }
  190. }))
  191. io.on('connection', ctrl.ws)
  192. // ----------------------------------------
  193. // Start child processes
  194. // ----------------------------------------
  195. let bgAgent = fork(path.join(SERVERPATH, 'agent.js'))
  196. bgAgent.on('message', m => {
  197. if (!m.action) {
  198. return
  199. }
  200. switch (m.action) {
  201. case 'searchAdd':
  202. search.add(m.content)
  203. break
  204. }
  205. })
  206. process.on('exit', (code) => {
  207. bgAgent.disconnect()
  208. })