All files / crowi index.js

70.17% Statements 127/181
51.67% Branches 31/60
80.95% Functions 34/42
70% Lines 126/180

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376    15x 15x 15x 15x 15x 15x 15x 15x 15x 15x       16x   16x 16x 16x 16x 16x 16x 16x 16x 16x 16x   16x 16x 16x 16x 16x 16x   16x   16x 16x 16x   16x 16x 16x 16x 16x 16x 16x   16x 16x 16x 16x   16x         15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x   15x       1x                           2x       67x       11x 11x                         1x       16x           16x           884x 226x     658x         204x 96x     108x         15x     15x           15x 15x       15x 15x           15x 15x           15x               15x 15x 15x                   15x               15x       15x 15x 225x   15x         16x 96x         15x       22x       14x               15x       15x 15x   15x       15x   15x 15x                           15x         15x       15x 15x   15x 15x             15x 15x                   15x           15x 15x       1x                                                         15x 15x 15x 15x 15x   15x 15x   15x 15x   15x           15x               15x 15x                     15x  
'use strict'
 
const debug = require('debug')('crowi:crowi')
const pkg = require('../../package.json')
const path = require('path')
const sep = path.sep
const uuidv4 = require('uuid/v4')
const mongoose = require('mongoose')
const models = require('../models')
const events = require('../events')
const middlewares = require('../middlewares')
const controllers = require('../controllers')
 
class Crowi {
  constructor(rootdir, env) {
    this.version = pkg.version
 
    this.rootDir = rootdir
    this.pluginDir = path.join(this.rootDir, 'node_modules') + sep
    this.publicDir = path.join(this.rootDir, 'public') + sep
    this.libDir = path.join(this.rootDir, 'lib') + sep
    this.localeDir = path.join(this.rootDir, 'locales') + sep
    this.resourceDir = path.join(this.rootDir, 'resource') + sep
    this.viewsDir = path.join(this.libDir, 'views') + sep
    this.mailDir = path.join(this.viewsDir, 'mail') + sep
    this.tmpDir = path.join(this.rootDir, 'tmp') + sep
    this.cacheDir = path.join(this.tmpDir, 'cache')
 
    this.app = null
    this.mongoose = null
    this.config = {}
    this.searcher = null
    this.mailer = {}
    this.lru = {}
 
    this.tokens = null
 
    this.models = {}
    this.events = {}
    this.setupEvents()
 
    this.env = env
    this.baseUrl = this.env.BASE_URL || null
    this.node_env = this.env.NODE_ENV || 'development'
    this.port = this.env.PORT || 3000
    this.redis = null
    this.redisUrl = this.env.REDISTOGO_URL || this.env.REDIS_URL || null
    this.redisOpts = this.buildRedisOpts(this.redisUrl)
 
    this.pubSubId = uuidv4()
    this.publisher = null
    this.subscriber = null
    this.configPubSubChannel = 'config'
 
    this.initialized = false
  }
 
  async init() {
    // setup database server and load all modesl
    await this.setupDatabase()
    await this.setupModels()
    await this.setupRedisClient()
    await this.setupSessionConfig()
    await this.setupConfig()
    await this.setupSearcher()
    await this.setupMailer()
    await this.setupSlack()
    await this.setupCsrf()
    await this.setupDNSCache()
    await this.setupLRU()
    await this.buildServer()
 
    this.initialized = true
  }
 
  isInitialized() {
    return this.initialized
  }
 
  isPageId(pageId) {
    if (!pageId) {
      return false
    }
 
    if (typeof pageId === 'string' && pageId.match(/^[\da-f]{24}$/)) {
      return true
    }
  }
 
  setConfig(config) {
    this.config.update(config)
  }
 
  getConfig() {
    return this.config.get()
  }
 
  getBaseUrl() {
    Eif (this.baseUrl) {
      return this.baseUrl
    }
    const config = this.getConfig()
    if (config && config.crowi && config.crowi['app:url']) {
      return config.crowi['app:url']
    }
 
    // This might be happend when env BASE_URL is not set and this is not an express request.
    // While initialize express, config.crowi['app:url'] could be set be detecting accessing URL.
    return null
  }
 
  getEnv() {
    return this.env
  }
 
  buildRedisOpts(redisUrl) {
    Iif (redisUrl) {
      const url = require('url')
      const { hostname: host, port, auth } = url.parse(redisUrl)
      const password = auth ? { password: auth.split(':')[1] } : {}
      return { host, port, ...password }
    }
    return null
  }
 
  // getter/setter of model instance
  //
  model(name, model) {
    if (model) {
      return (this.models[name] = model)
    }
 
    return this.models[name]
  }
 
  // getter/setter of event instance
  event(name, event) {
    if (event) {
      return (this.events[name] = event)
    }
 
    return this.events[name]
  }
 
  setupDatabase() {
    // mongoUri = mongodb://user:password@host/dbname
    mongoose.Promise = global.Promise
 
    var mongoUri =
      this.env.MONGOLAB_URI || // for B.C.
      this.env.MONGODB_URI || // MONGOLAB changes their env name
      this.env.MONGOHQ_URL ||
      this.env.MONGO_URI ||
      'mongodb://localhost/crowi'
 
    return new Promise((resolve, reject) => {
      const mongooseOptions = {
        useNewUrlParser: true,
        useFindAndModify: false,
      }
      mongoose.connect(mongoUri, mongooseOptions, e => {
        Iif (e) {
          debug('DB Connect Error: ', e)
          debug('DB Connect Error: ', mongoUri)
          return reject(new Error("Cann't connect to Database Server."))
        }
 
        this.mongoose = mongoose
        return resolve(mongoose)
      })
    })
  }
 
  async setupRedisClient() {
    Iif (this.redisOpts) {
      const redis = require('redis')
      const redisClient = redis.createClient(this.redisOpts)
      this.redis = redisClient
    }
  }
 
  setupSessionConfig() {
    const session = require('express-session')
    const sessionAge = 1000 * 3600 * 24 * 30
    const sessionConfig = {
      rolling: true,
      secret: this.env.SECRET_TOKEN || 'this is default session secret',
      resave: false,
      saveUninitialized: true,
      cookie: {
        maxAge: sessionAge,
      },
    }
 
    Iif (this.redis) {
      const RedisStore = require('connect-redis')(session)
      sessionConfig.store = new RedisStore({
        prefix: 'crowi:sess:',
        client: this.redis,
      })
    }
 
    this.sessionConfig = sessionConfig
  }
 
  setupModels() {
    return new Promise((resolve, reject) => {
      Object.keys(models).forEach(key => {
        this.model(key, models[key](this))
      })
      resolve()
    })
  }
 
  setupEvents() {
    return Object.entries(events).forEach(([key, Event]) => {
      this.event(key, new Event(this))
    })
  }
 
  getApp() {
    return this.app
  }
 
  getMongo() {
    return this.mongoose
  }
 
  getIo() {
    return this.io
  }
 
  getSearcher() {
    return this.searcher
  }
 
  getMailer() {
    return this.mailer
  }
 
  async setupConfig() {
    const Config = require('../service/config')
    this.config = new Config(this)
 
    return this.config.load()
  }
 
  setupSearcher() {
    const searcherUri = this.env.ELASTICSEARCH_URI || this.env.BONSAI_URL || null
 
    return new Promise((resolve, reject) => {
      Iif (searcherUri) {
        try {
          this.searcher = new (require(path.join(this.libDir, 'util', 'search')))(this, searcherUri)
 
          // workaround
          setTimeout(() => {
            this.searcher.checkESVersion()
            this.searcher.ensureAlias()
          }, 5000)
        } catch (e) {
          debug('Error on setup searcher', e)
          this.searcher = null
        }
      }
      resolve()
    })
  }
 
  setupMailer() {
    this.mailer = require('../util/mailer')(this)
  }
 
  setupSlack() {
    const config = this.getConfig()
    const Config = this.model('Config')
 
    Eif (!Config.hasSlackConfig(config)) {
      this.slack = {}
    } else {
      this.slack = require('../util/slack')(this)
    }
  }
 
  setupCsrf() {
    const Tokens = require('csrf')
    this.tokens = new Tokens()
  }
 
  async setupDNSCache() {
    /**
     * Enable dnscache
     * To prevent slow dns resolution in vm on linux.
     * In December 2018, linux kernel may have race in conntrack.
     * See: https://www.weave.works/blog/racy-conntrack-and-dns-lookup-timeouts
     */
    Eif (this.env.ENABLE_DNSCACHE !== 'true') return
 
    require('dnscache')({ enable: true })
  }
 
  setupLRU() {
    const LRU = require('../service/lru')
    this.lru = new LRU(this)
  }
 
  getTokens() {
    return this.tokens
  }
 
  async start() {
    if (this.app === null) {
      throw new Error('Must call init() before start().')
    }
 
    const http = require('http')
 
    const server = http.createServer(this.app).listen(this.port, () => {
      console.log('[' + this.node_env + '] Express server listening on port ' + this.port)
    })
    const io = require('socket.io')(server, { transports: ['websocket'] })
    if (this.redisOpts) {
      const redisAdapter = require('socket.io-redis')
      io.adapter(redisAdapter(this.redisOpts))
      debug('Using socket.io-redis')
    }
    io.sockets.on('connection', socket => {
      debug('Websocket CONNECTED, socket.id:', socket.id)
    })
 
    this.io = io
 
    return this.app
  }
 
  buildServer() {
    const express = require('express')
    const errorHandler = require('errorhandler')
    const morgan = require('morgan')
    const app = express()
    const env = this.node_env
 
    this.middlewares = middlewares(this, app)
    this.controllers = controllers(this, app)
 
    require('./express-init')(this, app)
    require('../routes')(this, app)
 
    Iif (env == 'development') {
      // swig.setDefaults({ cache: false });
      app.use(errorHandler({ dumpExceptions: true, showStack: true }))
      app.use(morgan('dev'))
    }
 
    Iif (env == 'production') {
      app.use(morgan('combined'))
      app.use(function(err, req, res, next) {
        res.status(500)
        res.render('500', { error: err })
      })
    }
 
    this.app = app
    return Promise.resolve(app)
  }
 
  exitOnError(err) {
    debug('Critical error occured.')
    console.error(err)
    console.error(err.stack)
    process.exit(1)
  }
}
 
module.exports = Crowi