index.js 6.95 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 14
const path = require('path')
const ROOTPATH = process.cwd()
const SERVERPATH = path.join(ROOTPATH, 'server')

global.ROOTPATH = ROOTPATH
global.SERVERPATH = SERVERPATH
NGPixel's avatar
NGPixel committed
15
const IS_DEBUG = process.env.NODE_ENV === 'development'
16

17 18
process.env.VIPS_WARNING = false

19 20 21
// if (IS_DEBUG) {
//   require('@glimpse/glimpse').init()
// }
22

23
let appconf = require('./libs/config')()
24 25 26
global.appconfig = appconf.config
global.appdata = appconf.data

NGPixel's avatar
NGPixel committed
27
// ----------------------------------------
28
// Load Winston
NGPixel's avatar
NGPixel committed
29 30
// ----------------------------------------

NGPixel's avatar
NGPixel committed
31
global.winston = require('./libs/logger')(IS_DEBUG, 'SERVER')
32
global.winston.info('Wiki.js is initializing...')
NGPixel's avatar
NGPixel committed
33

34 35 36
// ----------------------------------------
// Load global modules
// ----------------------------------------
37

38
global.lcdata = require('./libs/local').init()
39
global.db = require('./libs/db').init()
40 41 42 43
global.entries = require('./libs/entries').init()
global.git = require('./libs/git').init(false)
global.lang = require('i18next')
global.mark = require('./libs/markdown')
44
global.search = require('./libs/search').init()
45
global.upl = require('./libs/uploads').init()
46 47 48 49

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

51 52 53 54 55 56 57 58 59
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')
60
const i18nBackend = require('i18next-node-fs-backend')
61 62 63 64
const passport = require('passport')
const passportSocketIo = require('passport.socketio')
const session = require('express-session')
const SessionMongoStore = require('connect-mongo')(session)
65
const graceful = require('node-graceful')
66 67
const socketio = require('socket.io')

68 69
var mw = autoload(path.join(SERVERPATH, '/middlewares'))
var ctrl = autoload(path.join(SERVERPATH, '/controllers'))
NGPixel's avatar
NGPixel committed
70 71 72 73 74

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

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

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

83
app.use(mw.security)
NGPixel's avatar
NGPixel committed
84 85

// ----------------------------------------
86 87 88
// Public Assets
// ----------------------------------------

89
app.use(favicon(path.join(ROOTPATH, 'assets', 'favicon.ico')))
90 91 92 93
app.use(express.static(path.join(ROOTPATH, 'assets'), {
  index: false,
  maxAge: '7d'
}))
94 95

// ----------------------------------------
NGPixel's avatar
NGPixel committed
96
// Passport Authentication
NGPixel's avatar
NGPixel committed
97 98
// ----------------------------------------

99 100
require('./libs/auth')(passport)
global.rights = require('./libs/rights')
101
global.rights.init()
NGPixel's avatar
NGPixel committed
102

103
let sessionStore = new SessionMongoStore({
104
  mongooseConnection: global.db.connection,
105
  touchAfter: 15
106
})
NGPixel's avatar
NGPixel committed
107

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

120 121 122 123 124 125
// ----------------------------------------
// SEO
// ----------------------------------------

app.use(mw.seo)

NGPixel's avatar
NGPixel committed
126 127 128 129
// ----------------------------------------
// Localization Engine
// ----------------------------------------

130 131
global.lang
  .use(i18nBackend)
NGPixel's avatar
NGPixel committed
132 133
  .init({
    load: 'languageOnly',
NGPixel's avatar
NGPixel committed
134
    ns: ['common', 'admin', 'auth', 'errors', 'git'],
NGPixel's avatar
NGPixel committed
135 136
    defaultNS: 'common',
    saveMissing: false,
137 138
    preload: [appconfig.lang],
    lng: appconfig.lang,
139
    fallbackLng: 'en',
NGPixel's avatar
NGPixel committed
140
    backend: {
141
      loadPath: path.join(SERVERPATH, 'locales/{{lng}}/{{ns}}.json')
NGPixel's avatar
NGPixel committed
142
    }
143
  })
NGPixel's avatar
NGPixel committed
144 145 146 147 148

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

149
app.set('views', path.join(SERVERPATH, 'views'))
150
app.set('view engine', 'pug')
NGPixel's avatar
NGPixel committed
151

152 153
app.use(bodyParser.json({ limit: '1mb' }))
app.use(bodyParser.urlencoded({ extended: false, limit: '1mb' }))
NGPixel's avatar
NGPixel committed
154 155 156 157 158

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

159
app.locals._ = require('lodash')
160
app.locals.t = global.lang.t.bind(global.lang)
161
app.locals.moment = require('moment')
162
app.locals.moment.locale(appconfig.lang)
163 164
app.locals.appconfig = appconfig
app.use(mw.flash)
NGPixel's avatar
NGPixel committed
165 166 167 168 169

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

170
app.use('/', ctrl.auth)
NGPixel's avatar
NGPixel committed
171

172 173 174
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
175 176 177 178 179

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

180 181 182 183 184
app.use(function (req, res, next) {
  var err = new Error('Not Found')
  err.status = 404
  next(err)
})
NGPixel's avatar
NGPixel committed
185

186 187
app.use(function (err, req, res, next) {
  res.status(err.status || 500)
NGPixel's avatar
NGPixel committed
188 189
  res.render('error', {
    message: err.message,
NGPixel's avatar
NGPixel committed
190
    error: IS_DEBUG ? err : {}
191 192
  })
})
NGPixel's avatar
NGPixel committed
193 194 195 196 197

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

198
global.winston.info('Starting HTTP/WS server on port ' + appconfig.port + '...')
NGPixel's avatar
NGPixel committed
199

200 201 202
app.set('port', appconfig.port)
var server = http.createServer(app)
var io = socketio(server)
203

204
server.listen(appconfig.port)
NGPixel's avatar
NGPixel committed
205 206
server.on('error', (error) => {
  if (error.syscall !== 'listen') {
207
    throw error
NGPixel's avatar
NGPixel committed
208 209 210 211 212
  }

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
213
      global.winston.error('Listening on port ' + appconfig.port + ' requires elevated privileges!')
NGPixel's avatar
NGPixel committed
214
      return process.exit(1)
NGPixel's avatar
NGPixel committed
215
    case 'EADDRINUSE':
216
      global.winston.error('Port ' + appconfig.port + ' is already in use!')
NGPixel's avatar
NGPixel committed
217
      return process.exit(1)
NGPixel's avatar
NGPixel committed
218
    default:
219
      throw error
NGPixel's avatar
NGPixel committed
220
  }
221
})
NGPixel's avatar
NGPixel committed
222 223

server.on('listening', () => {
224
  global.winston.info('HTTP/WS server started successfully! [RUNNING]')
225
})
226 227

// ----------------------------------------
228
// WebSocket
229 230
// ----------------------------------------

231
io.use(passportSocketIo.authorize({
232
  key: 'wikijs.sid',
233 234 235 236
  store: sessionStore,
  secret: appconfig.sessionSecret,
  cookieParser,
  success: (data, accept) => {
237
    accept()
238 239
  },
  fail: (data, message, error, accept) => {
240
    accept()
241
  }
242
}))
243

244
io.on('connection', ctrl.ws)
245 246

// ----------------------------------------
247
// Start child processes
248 249
// ----------------------------------------

250
let bgAgent = fork(path.join(SERVERPATH, 'agent.js'))
251 252 253 254 255 256 257 258

bgAgent.on('message', m => {
  if (!m.action) {
    return
  }

  switch (m.action) {
    case 'searchAdd':
259
      global.search.add(m.content)
260 261 262
      break
  }
})
263

264 265 266 267 268 269 270 271 272 273
// ----------------------------------------
// Graceful shutdown
// ----------------------------------------

graceful.on('exit', () => {
  global.winston.info('- SHUTTING DOWN - Performing git sync...')
  return global.git.resync().then(() => {
    global.winston.info('- SHUTTING DOWN - Git sync successful. Now safe to exit.')
    process.kill(process.pid, 'SIGINT')
  })
274
})