server.js 6.36 KB
Newer Older
1 2
'use strict'

NGPixel's avatar
NGPixel committed
3
// ===========================================
4
// Wiki.js
NGPixel's avatar
NGPixel committed
5 6 7 8
// 1.0.0
// Licensed under AGPLv3
// ===========================================

9 10 11 12 13
global.PROCNAME = 'SERVER'
global.ROOTPATH = __dirname
global.IS_DEBUG = process.env.NODE_ENV === 'development'
if (IS_DEBUG) {
  global.CORE_PATH = ROOTPATH + '/../core/'
14
} else {
15
  global.CORE_PATH = ROOTPATH + '/node_modules/requarks-core/'
16
}
17

18 19
process.env.VIPS_WARNING = false

NGPixel's avatar
NGPixel committed
20
// ----------------------------------------
21
// Load Winston
NGPixel's avatar
NGPixel committed
22 23
// ----------------------------------------

24 25
global.winston = require(CORE_PATH + 'core-libs/winston')(IS_DEBUG)
winston.info('[SERVER] Wiki.js is initializing...')
NGPixel's avatar
NGPixel committed
26

27 28 29
// ----------------------------------------
// Load global modules
// ----------------------------------------
30

31 32 33 34 35 36 37 38 39 40
let appconf = require(CORE_PATH + 'core-libs/config')()
global.appconfig = appconf.config
global.appdata = appconf.data
global.lcdata = require('./libs/local').init()
global.db = require(CORE_PATH + 'core-libs/mongodb').init()
global.entries = require('./libs/entries').init()
global.git = require('./libs/git').init(false)
global.lang = require('i18next')
global.mark = require('./libs/markdown')
global.upl = require('./libs/uploads').init()
41 42 43 44

// ----------------------------------------
// Load modules
// ----------------------------------------
NGPixel's avatar
NGPixel committed
45

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
const autoload = require('auto-load')
const bodyParser = require('body-parser')
const compression = require('compression')
const cookieParser = require('cookie-parser')
const express = require('express')
const favicon = require('serve-favicon')
const flash = require('connect-flash')
const fork = require('child_process').fork
const http = require('http')
const i18nextBackend = require('i18next-node-fs-backend')
const i18nextMw = require('i18next-express-middleware')
const passport = require('passport')
const passportSocketIo = require('passport.socketio')
const path = require('path')
const session = require('express-session')
const SessionMongoStore = require('connect-mongo')(session)
const socketio = require('socket.io')

var mw = autoload(CORE_PATH + '/core-middlewares')
var ctrl = autoload(path.join(ROOTPATH, '/controllers'))
var libInternalAuth = require('./libs/internalAuth')

global.WSInternalKey = libInternalAuth.generateKey()
NGPixel's avatar
NGPixel committed
69 70 71 72 73

// ----------------------------------------
// Define Express App
// ----------------------------------------

74 75
global.app = express()
app.use(compression())
NGPixel's avatar
NGPixel committed
76 77 78 79 80

// ----------------------------------------
// Security
// ----------------------------------------

81
app.use(mw.security)
NGPixel's avatar
NGPixel committed
82 83

// ----------------------------------------
84 85 86
// Public Assets
// ----------------------------------------

87 88
app.use(favicon(path.join(ROOTPATH, 'assets', 'favicon.ico')))
app.use(express.static(path.join(ROOTPATH, 'assets')))
89 90

// ----------------------------------------
NGPixel's avatar
NGPixel committed
91
// Passport Authentication
NGPixel's avatar
NGPixel committed
92 93
// ----------------------------------------

94 95 96
require(CORE_PATH + 'core-libs/auth')(passport)
global.rights = require(CORE_PATH + 'core-libs/rights')
rights.init()
NGPixel's avatar
NGPixel committed
97

98
var sessionStore = new SessionMongoStore({
99 100
  mongooseConnection: db.connection,
  touchAfter: 15
101
})
NGPixel's avatar
NGPixel committed
102

103
app.use(cookieParser())
NGPixel's avatar
NGPixel committed
104 105
app.use(session({
  name: 'requarkswiki.sid',
106
  store: sessionStore,
NGPixel's avatar
NGPixel committed
107 108 109
  secret: appconfig.sessionSecret,
  resave: false,
  saveUninitialized: false
110 111 112 113
}))
app.use(flash())
app.use(passport.initialize())
app.use(passport.session())
NGPixel's avatar
NGPixel committed
114 115 116 117 118 119

// ----------------------------------------
// Localization Engine
// ----------------------------------------

lang
120 121
  .use(i18nextBackend)
  .use(i18nextMw.LanguageDetector)
NGPixel's avatar
NGPixel committed
122 123
  .init({
    load: 'languageOnly',
NGPixel's avatar
NGPixel committed
124
    ns: ['common', 'auth'],
NGPixel's avatar
NGPixel committed
125 126 127 128
    defaultNS: 'common',
    saveMissing: false,
    supportedLngs: ['en', 'fr'],
    preload: ['en', 'fr'],
129
    fallbackLng: 'en',
NGPixel's avatar
NGPixel committed
130 131 132
    backend: {
      loadPath: './locales/{{lng}}/{{ns}}.json'
    }
133
  })
NGPixel's avatar
NGPixel committed
134 135 136 137 138

// ----------------------------------------
// View Engine Setup
// ----------------------------------------

139 140 141
app.use(i18nextMw.handle(lang))
app.set('views', path.join(ROOTPATH, 'views'))
app.set('view engine', 'pug')
NGPixel's avatar
NGPixel committed
142

143 144
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
NGPixel's avatar
NGPixel committed
145 146 147 148 149

// ----------------------------------------
// View accessible data
// ----------------------------------------

150 151 152 153
app.locals._ = require('lodash')
app.locals.moment = require('moment')
app.locals.appconfig = appconfig
app.use(mw.flash)
NGPixel's avatar
NGPixel committed
154 155 156 157 158

// ----------------------------------------
// Controllers
// ----------------------------------------

159
app.use('/', ctrl.auth)
NGPixel's avatar
NGPixel committed
160

161 162 163
app.use('/uploads', mw.auth, ctrl.uploads)
app.use('/admin', mw.auth, ctrl.admin)
app.use('/', mw.auth, ctrl.pages)
NGPixel's avatar
NGPixel committed
164 165 166 167 168

// ----------------------------------------
// Error handling
// ----------------------------------------

169 170 171 172 173
app.use(function (req, res, next) {
  var err = new Error('Not Found')
  err.status = 404
  next(err)
})
NGPixel's avatar
NGPixel committed
174

175 176
app.use(function (err, req, res, next) {
  res.status(err.status || 500)
NGPixel's avatar
NGPixel committed
177 178
  res.render('error', {
    message: err.message,
NGPixel's avatar
NGPixel committed
179
    error: IS_DEBUG ? err : {}
180 181
  })
})
NGPixel's avatar
NGPixel committed
182 183 184 185 186

// ----------------------------------------
// Start HTTP server
// ----------------------------------------

187
winston.info('[SERVER] Starting HTTP/WS server on port ' + appconfig.port + '...')
NGPixel's avatar
NGPixel committed
188

189 190 191
app.set('port', appconfig.port)
var server = http.createServer(app)
var io = socketio(server)
192

193
server.listen(appconfig.port)
NGPixel's avatar
NGPixel committed
194 195
server.on('error', (error) => {
  if (error.syscall !== 'listen') {
196
    throw error
NGPixel's avatar
NGPixel committed
197 198 199 200 201
  }

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
202 203 204
      console.error('Listening on port ' + appconfig.port + ' requires elevated privileges!')
      process.exit(1)
      break
NGPixel's avatar
NGPixel committed
205
    case 'EADDRINUSE':
206 207 208
      console.error('Port ' + appconfig.port + ' is already in use!')
      process.exit(1)
      break
NGPixel's avatar
NGPixel committed
209
    default:
210
      throw error
NGPixel's avatar
NGPixel committed
211
  }
212
})
NGPixel's avatar
NGPixel committed
213 214

server.on('listening', () => {
215 216
  winston.info('[SERVER] HTTP/WS server started successfully! [RUNNING]')
})
217 218

// ----------------------------------------
219
// WebSocket
220 221
// ----------------------------------------

222 223 224 225 226 227 228
io.use(passportSocketIo.authorize({
  key: 'requarkswiki.sid',
  store: sessionStore,
  secret: appconfig.sessionSecret,
  passport,
  cookieParser,
  success: (data, accept) => {
229
    accept()
230 231
  },
  fail: (data, message, error, accept) => {
232
    return accept(new Error(message))
233
  }
234
}))
235

236
io.on('connection', ctrl.ws)
237 238

// ----------------------------------------
239
// Start child processes
240 241
// ----------------------------------------

242
global.bgAgent = fork('agent.js')
243

244
process.on('exit', (code) => {
245 246
  bgAgent.disconnect()
})