index.js 6.44 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
let appconf = require('./libs/config')()
20 21 22
global.appconfig = appconf.config
global.appdata = appconf.data

NGPixel's avatar
NGPixel committed
23
// ----------------------------------------
24
// Load Winston
NGPixel's avatar
NGPixel committed
25 26
// ----------------------------------------

NGPixel's avatar
NGPixel committed
27 28
global.winston = require('./libs/logger')(IS_DEBUG, 'SERVER')
winston.info('Wiki.js is initializing...')
NGPixel's avatar
NGPixel committed
29

30 31 32
// ----------------------------------------
// Load global modules
// ----------------------------------------
33

34
global.lcdata = require('./libs/local').init()
35
global.db = require('./libs/db').init()
36 37 38 39
global.entries = require('./libs/entries').init()
global.git = require('./libs/git').init(false)
global.lang = require('i18next')
global.mark = require('./libs/markdown')
40
global.search = require('./libs/search').init()
41
global.upl = require('./libs/uploads').init()
42 43 44 45

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

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
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 session = require('express-session')
const SessionMongoStore = require('connect-mongo')(session)
const socketio = require('socket.io')

64 65
var mw = autoload(path.join(SERVERPATH, '/middlewares'))
var ctrl = autoload(path.join(SERVERPATH, '/controllers'))
NGPixel's avatar
NGPixel committed
66 67 68 69 70

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

71 72
global.app = express()
app.use(compression())
NGPixel's avatar
NGPixel committed
73 74 75 76 77

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

78
app.use(mw.security)
NGPixel's avatar
NGPixel committed
79 80

// ----------------------------------------
81 82 83
// Public Assets
// ----------------------------------------

84 85
app.use(favicon(path.join(ROOTPATH, 'assets', 'favicon.ico')))
app.use(express.static(path.join(ROOTPATH, 'assets')))
86 87

// ----------------------------------------
NGPixel's avatar
NGPixel committed
88
// Passport Authentication
NGPixel's avatar
NGPixel committed
89 90
// ----------------------------------------

91 92
require('./libs/auth')(passport)
global.rights = require('./libs/rights')
93
rights.init()
NGPixel's avatar
NGPixel committed
94

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

100
app.use(cookieParser())
NGPixel's avatar
NGPixel committed
101 102
app.use(session({
  name: 'requarkswiki.sid',
103
  store: sessionStore,
NGPixel's avatar
NGPixel committed
104 105 106
  secret: appconfig.sessionSecret,
  resave: false,
  saveUninitialized: false
107 108 109 110
}))
app.use(flash())
app.use(passport.initialize())
app.use(passport.session())
NGPixel's avatar
NGPixel committed
111

112 113 114 115 116 117
// ----------------------------------------
// SEO
// ----------------------------------------

app.use(mw.seo)

NGPixel's avatar
NGPixel committed
118 119 120 121 122
// ----------------------------------------
// Localization Engine
// ----------------------------------------

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

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

142
app.use(i18nextMw.handle(lang))
143
app.set('views', path.join(SERVERPATH, 'views'))
144
app.set('view engine', 'pug')
NGPixel's avatar
NGPixel committed
145

146 147
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
NGPixel's avatar
NGPixel committed
148 149 150 151 152

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

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

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

162
app.use('/', ctrl.auth)
NGPixel's avatar
NGPixel committed
163

164 165 166
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
167 168 169 170 171

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

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

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

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

NGPixel's avatar
NGPixel committed
190
winston.info('Starting HTTP/WS server on port ' + appconfig.port + '...')
NGPixel's avatar
NGPixel committed
191

192 193 194
app.set('port', appconfig.port)
var server = http.createServer(app)
var io = socketio(server)
195

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

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

server.on('listening', () => {
NGPixel's avatar
NGPixel committed
216
  winston.info('HTTP/WS server started successfully! [RUNNING]')
217
})
218 219

// ----------------------------------------
220
// WebSocket
221 222
// ----------------------------------------

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

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

// ----------------------------------------
240
// Start child processes
241 242
// ----------------------------------------

243
let bgAgent = fork(path.join(SERVERPATH, 'agent.js'))
244 245 246 247 248 249 250 251 252 253 254 255

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

  switch (m.action) {
    case 'searchAdd':
      search.add(m.content)
      break
  }
})
256

257
process.on('exit', (code) => {
258 259
  bgAgent.disconnect()
})