Jelajahi Sumber

WIP: apply to src/server

Yuki Takei 7 tahun lalu
induk
melakukan
326ccdd4ec
53 mengubah file dengan 350 tambahan dan 437 penghapusan
  1. 4 4
      src/server/app.js
  2. 4 6
      src/server/crowi/dev.js
  3. 51 53
      src/server/crowi/express-init.js
  4. 67 75
      src/server/crowi/index.js
  5. 3 3
      src/server/events/page.js
  6. 3 5
      src/server/form/admin/app.js
  7. 3 5
      src/server/form/admin/aws.js
  8. 3 5
      src/server/form/admin/custombehavior.js
  9. 3 5
      src/server/form/admin/customcss.js
  10. 3 5
      src/server/form/admin/customfeatures.js
  11. 3 5
      src/server/form/admin/customheader.js
  12. 3 5
      src/server/form/admin/customhighlightJsStyle.js
  13. 3 5
      src/server/form/admin/customlayout.js
  14. 3 5
      src/server/form/admin/customscript.js
  15. 3 5
      src/server/form/admin/customtheme.js
  16. 3 5
      src/server/form/admin/customtitle.js
  17. 2 4
      src/server/form/admin/importerEsa.js
  18. 2 4
      src/server/form/admin/importerQiita.js
  19. 3 6
      src/server/form/admin/mail.js
  20. 3 5
      src/server/form/admin/markdown.js
  21. 3 4
      src/server/form/admin/markdownPresentation.js
  22. 3 4
      src/server/form/admin/markdownXss.js
  23. 1 3
      src/server/form/admin/notificationGlobal.js
  24. 3 5
      src/server/form/admin/plugin.js
  25. 1 2
      src/server/form/admin/securityGeneral.js
  26. 3 5
      src/server/form/admin/securityGoogle.js
  27. 3 5
      src/server/form/admin/securityMechanism.js
  28. 2 4
      src/server/form/admin/securityPassportGitHub.js
  29. 2 4
      src/server/form/admin/securityPassportGoogle.js
  30. 3 5
      src/server/form/admin/securityPassportLdap.js
  31. 1 2
      src/server/form/admin/securityPassportSaml.js
  32. 2 4
      src/server/form/admin/securityPassportTwitter.js
  33. 3 4
      src/server/form/admin/siteUrl.js
  34. 3 5
      src/server/form/admin/slackIwhSetting.js
  35. 3 4
      src/server/form/admin/slackSetting.js
  36. 3 4
      src/server/form/admin/userGroupCreate.js
  37. 3 4
      src/server/form/admin/userInvite.js
  38. 2 3
      src/server/form/comment.js
  39. 2 4
      src/server/form/invited.js
  40. 2 3
      src/server/form/login.js
  41. 3 5
      src/server/form/me/apiToken.js
  42. 3 4
      src/server/form/me/imagetype.js
  43. 2 3
      src/server/form/me/password.js
  44. 3 4
      src/server/form/me/user.js
  45. 2 3
      src/server/form/register.js
  46. 4 5
      src/server/form/revision.js
  47. 1 0
      src/server/models/GlobalNotificationSetting.js
  48. 7 7
      src/server/models/attachment.js
  49. 11 11
      src/server/models/bookmark.js
  50. 31 33
      src/server/models/comment.js
  51. 53 54
      src/server/models/config.js
  52. 10 13
      src/server/models/external-account.js
  53. 0 2
      src/server/models/index.js

+ 4 - 4
src/server/app.js

@@ -12,9 +12,9 @@ const helpers = require('@commons/util/helpers');
 const growi = new (require('./crowi'))(helpers.root());
 
 
-/************************************
+/** **********************************
  *          Main Process
- ***********************************/
+ ********************************** */
 process.on('uncaughtException', (err) => {
   logger.error('Uncaught Exception: ', err);
 });
@@ -24,7 +24,7 @@ process.on('unhandledRejection', (reason, p) => {
 });
 
 growi.start()
-  .then(server => {
+  .then((server) => {
     if (helpers.hasProcessFlag('ci')) {
       logger.info('"--ci" flag is detected. Exit process.');
       server.close(() => {
@@ -32,7 +32,7 @@ growi.start()
       });
     }
   })
-  .catch(err => {
+  .catch((err) => {
     logger.error('An error occurred, unable to start the server');
     logger.error(err);
     process.exit(1);

+ 4 - 6
src/server/crowi/dev.js

@@ -7,7 +7,6 @@ const onHeaders = require('on-headers');
 
 
 class CrowiDev {
-
   /**
    * Creates an instance of CrowiDev.
    * @param {Crowi} crowi
@@ -27,7 +26,7 @@ class CrowiDev {
 
   initPromiseRejectionWarningHandler() {
     // https://qiita.com/syuilo/items/0800d7e44e93203c7285
-    process.on('unhandledRejection', console.dir);  // eslint-disable-line no-console
+    process.on('unhandledRejection', console.dir); // eslint-disable-line no-console
   }
 
   initSwig() {
@@ -40,10 +39,10 @@ class CrowiDev {
   requireForAutoReloadServer() {
     // load all json files for live reloading
     fs.readdirSync(this.crowi.localeDir)
-      .filter(filename => {
+      .filter((filename) => {
         return fs.statSync(path.join(this.crowi.localeDir, filename)).isDirectory();
       })
-      .map((dirname) => {
+      .forEach((dirname) => {
         require(path.join(this.crowi.localeDir, dirname, 'translation.json'));
       });
   }
@@ -119,7 +118,7 @@ class CrowiDev {
         `${this.crowi.viewsDir}/**/*.html`,
         `${this.crowi.publicDir}/**/*.js`,
         `${this.crowi.publicDir}/**/*.css`,
-      ]
+      ],
     });
     app.use(require('connect-browser-sync')(bs));
   }
@@ -127,7 +126,6 @@ class CrowiDev {
   loadPlugins(app) {
     if (process.env.PLUGIN_NAMES_TOBE_LOADED !== undefined
         && process.env.PLUGIN_NAMES_TOBE_LOADED.length > 0) {
-
       const pluginNames = process.env.PLUGIN_NAMES_TOBE_LOADED.split(',');
       logger.debug('[development] loading Plugins', pluginNames);
 

+ 51 - 53
src/server/crowi/express-init.js

@@ -1,33 +1,31 @@
-'use strict';
 
-module.exports = function(crowi, app) {
-  const debug = require('debug')('growi:crowi:express-init')
-    , path           = require('path')
-    , express        = require('express')
-    , helmet         = require('helmet')
-    , bodyParser     = require('body-parser')
-    , cookieParser   = require('cookie-parser')
-    , methodOverride = require('method-override')
-    , passport       = require('passport')
-    , session        = require('express-session')
-    , sanitizer      = require('express-sanitizer')
-    , basicAuth      = require('basic-auth-connect')
-    , flash          = require('connect-flash')
-    , swig           = require('swig-templates')
-    , webpackAssets  = require('express-webpack-assets')
-    , i18next        = require('i18next')
-    , i18nFsBackend  = require('i18next-node-fs-backend')
-    , i18nSprintf    = require('i18next-sprintf-postprocessor')
-    , i18nMiddleware = require('i18next-express-middleware')
-    , i18nUserSettingDetector  = require('../util/i18nUserSettingDetector')
-    , env            = crowi.node_env
-    , config         = crowi.getConfig()
-    , middleware     = require('../util/middlewares')
-
-    , Config = crowi.model('Config')
-    , User = crowi.model('User')
-    ;
 
+module.exports = function(crowi, app) {
+  const debug = require('debug')('growi:crowi:express-init');
+  const path = require('path');
+  const express = require('express');
+  const helmet = require('helmet');
+  const bodyParser = require('body-parser');
+  const cookieParser = require('cookie-parser');
+  const methodOverride = require('method-override');
+  const passport = require('passport');
+  const session = require('express-session');
+  const sanitizer = require('express-sanitizer');
+  const basicAuth = require('basic-auth-connect');
+  const flash = require('connect-flash');
+  const swig = require('swig-templates');
+  const webpackAssets = require('express-webpack-assets');
+  const i18next = require('i18next');
+  const i18nFsBackend = require('i18next-node-fs-backend');
+  const i18nSprintf = require('i18next-sprintf-postprocessor');
+  const i18nMiddleware = require('i18next-express-middleware');
+  const i18nUserSettingDetector = require('../util/i18nUserSettingDetector');
+  const env = crowi.node_env;
+  const config = crowi.getConfig();
+  const middleware = require('../util/middlewares');
+
+
+  const User = crowi.model('User');
   const lngDetector = new i18nMiddleware.LanguageDetector();
   lngDetector.addDetector(i18nUserSettingDetector);
 
@@ -38,9 +36,9 @@ module.exports = function(crowi, app) {
     .init({
       // debug: true,
       fallbackLng: [User.LANG_EN_US],
-      whitelist: Object.keys(User.getLanguageLabels()).map((k) => User[k]),
+      whitelist: Object.keys(User.getLanguageLabels()).map((k) => { return User[k] }),
       backend: {
-        loadPath: crowi.localeDir + '{{lng}}/translation.json'
+        loadPath: `${crowi.localeDir}{{lng}}/translation.json`,
       },
       detection: {
         order: ['userSettingDetector', 'header', 'navigator'],
@@ -48,31 +46,31 @@ module.exports = function(crowi, app) {
       overloadTranslationOptionHandler: i18nSprintf.overloadTranslationOptionHandler,
 
       // change nsSeparator from ':' to '::' because ':' is used in config keys and these are used in i18n keys
-      nsSeparator: '::'
+      nsSeparator: '::',
     });
 
   app.use(helmet());
 
-  app.use(function(req, res, next) {
-    const now = new Date()
-      , tzoffset = -(config.crowi['app:timezone'] || 9) * 60 // for datez
-      , Page = crowi.model('Page')
-      , User = crowi.model('User')
-      , Config = crowi.model('Config')
-      ;
+  app.use((req, res, next) => {
+    const now = new Date();
+    const tzoffset = -(config.crowi['app:timezone'] || 9) * 60;
+    // for datez
 
+    const Page = crowi.model('Page');
+    const User = crowi.model('User');
+    const Config = crowi.model('Config');
     app.set('tzoffset', tzoffset);
 
     req.config = config;
     req.csrfToken = null;
 
-    res.locals.req      = req;
-    res.locals.baseUrl  = crowi.configManager.getSiteUrl();
-    res.locals.config   = config;
-    res.locals.env      = env;
-    res.locals.now      = now;
+    res.locals.req = req;
+    res.locals.baseUrl = crowi.configManager.getSiteUrl();
+    res.locals.config = config;
+    res.locals.env = env;
+    res.locals.now = now;
     res.locals.tzoffset = tzoffset;
-    res.locals.consts   = {
+    res.locals.consts = {
       pageGrants: Page.getGrantLabels(),
       userStatus: User.getUserStatusLabels(),
       language:   User.getLanguageLabels(),
@@ -85,25 +83,25 @@ module.exports = function(crowi, app) {
   });
 
   app.set('port', crowi.port);
-  const staticOption = (crowi.node_env === 'production') ? {maxAge: '30d'} : {};
+  const staticOption = (crowi.node_env === 'production') ? { maxAge: '30d' } : {};
   app.use(express.static(crowi.publicDir, staticOption));
   app.engine('html', swig.renderFile);
   app.use(webpackAssets(
     path.join(crowi.publicDir, 'manifest.json'),
-    { devMode: (crowi.node_env === 'development') })
-  );
+    { devMode: (crowi.node_env === 'development') },
+  ));
   // app.set('view cache', false);  // Default: true in production, otherwise undefined. -- 2017.07.04 Yuki Takei
   app.set('view engine', 'html');
   app.set('views', crowi.viewsDir);
   app.use(methodOverride());
   app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' }));
-  app.use(bodyParser.json({limit: '50mb'}));
+  app.use(bodyParser.json({ limit: '50mb' }));
   app.use(sanitizer());
   app.use(cookieParser());
   app.use(session(crowi.sessionConfig));
 
   // Set basic auth middleware
-  app.use(function(req, res, next) {
+  app.use((req, res, next) => {
     if (req.query.access_token || req.body.access_token) {
       return next();
     }
@@ -119,11 +117,11 @@ module.exports = function(crowi, app) {
     if (config.crowi['security:basicName'] && config.crowi['security:basicSecret']) {
       return basicAuth(
         config.crowi['security:basicName'],
-        config.crowi['security:basicSecret'])(req, res, next);
-    }
-    else {
-      next();
+        config.crowi['security:basicSecret'],
+      )(req, res, next);
     }
+
+    next();
   });
 
   // passport

+ 67 - 75
src/server/crowi/index.js

@@ -1,37 +1,35 @@
-'use strict';
 
 
-const debug = require('debug')('growi:crowi')
-  , logger = require('@alias/logger')('growi:crowi')
-  , pkg = require('@root/package.json')
-  , InterceptorManager = require('@commons/service/interceptor-manager')
-  , CdnResourcesService = require('@commons/service/cdn-resources-service')
-  , Xss = require('@commons/service/xss')
-  , path = require('path')
-  , sep = path.sep
+const debug = require('debug')('growi:crowi');
+const logger = require('@alias/logger')('growi:crowi');
+const pkg = require('@root/package.json');
+const InterceptorManager = require('@commons/service/interceptor-manager');
+const CdnResourcesService = require('@commons/service/cdn-resources-service');
+const Xss = require('@commons/service/xss');
+const path = require('path');
 
-  , mongoose    = require('mongoose')
+const sep = path.sep;
 
-  , models = require('../models')
+const mongoose = require('mongoose');
 
-  ;
+const models = require('../models');
 
 function Crowi(rootdir) {
   const self = this;
 
   this.version = pkg.version;
-  this.runtimeVersions = undefined;   // initialized by scanRuntimeVersions()
-
-  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, 'src/server') + sep;
-  this.eventsDir   = path.join(this.libDir, 'events') + sep;
-  this.viewsDir    = path.join(this.libDir, 'views') + sep;
+  this.runtimeVersions = undefined; // initialized by scanRuntimeVersions()
+
+  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, 'src/server') + sep;
+  this.eventsDir = path.join(this.libDir, 'events') + sep;
+  this.viewsDir = path.join(this.libDir, 'views') + sep;
   this.resourceDir = path.join(this.rootDir, 'resource') + sep;
-  this.localeDir   = path.join(this.resourceDir, 'locales') + sep;
-  this.tmpDir      = path.join(this.rootDir, 'tmp') + sep;
-  this.cacheDir    = path.join(this.tmpDir, 'cache');
+  this.localeDir = path.join(this.resourceDir, 'locales') + sep;
+  this.tmpDir = path.join(this.rootDir, 'tmp') + sep;
+  this.cacheDir = path.join(this.tmpDir, 'cache');
 
   this.config = {};
   this.configManager = null;
@@ -54,20 +52,19 @@ function Crowi(rootdir) {
   this.port = this.env.PORT || 3000;
 
   this.events = {
-    user: new (require(self.eventsDir + 'user'))(this),
-    page: new (require(self.eventsDir + 'page'))(this),
-    search: new (require(self.eventsDir + 'search'))(this),
-    bookmark: new (require(self.eventsDir + 'bookmark'))(this),
+    user: new (require(`${self.eventsDir}user`))(this),
+    page: new (require(`${self.eventsDir}page`))(this),
+    search: new (require(`${self.eventsDir}search`))(this),
+    bookmark: new (require(`${self.eventsDir}bookmark`))(this),
   };
-
 }
 
 function getMongoUrl(env) {
-  return env.MONGOLAB_URI || // for B.C.
-    env.MONGODB_URI || // MONGOLAB changes their env name
-    env.MONGOHQ_URL ||
-    env.MONGO_URI ||
-    ((process.env.NODE_ENV === 'test') ? 'mongodb://localhost/growi_test' : 'mongodb://localhost/growi');
+  return env.MONGOLAB_URI // for B.C.
+    || env.MONGODB_URI // MONGOLAB changes their env name
+    || env.MONGOHQ_URL
+    || env.MONGO_URI
+    || ((process.env.NODE_ENV === 'test') ? 'mongodb://localhost/growi_test' : 'mongodb://localhost/growi');
 }
 
 Crowi.prototype.init = async function() {
@@ -142,15 +139,15 @@ Crowi.prototype.setupDatabase = function() {
 };
 
 Crowi.prototype.setupSessionConfig = function() {
-  const self = this
-    , session  = require('express-session')
-    , sessionAge = (1000*3600*24*30)
-    , redisUrl = this.env.REDISTOGO_URL || this.env.REDIS_URI || this.env.REDIS_URL || null
-    , mongoUrl = getMongoUrl(this.env)
-    ;
+  const self = this;
+  const session = require('express-session');
+  const sessionAge = (1000 * 3600 * 24 * 30);
+  const redisUrl = this.env.REDISTOGO_URL || this.env.REDIS_URI || this.env.REDIS_URL || null;
+
+  const mongoUrl = getMongoUrl(this.env);
   let sessionConfig;
 
-  return new Promise(function(resolve, reject) {
+  return new Promise(((resolve, reject) => {
     sessionConfig = {
       rolling: true,
       secret: self.env.SECRET_TOKEN || 'this is default session secret',
@@ -178,13 +175,13 @@ Crowi.prototype.setupSessionConfig = function() {
 
     self.sessionConfig = sessionConfig;
     resolve();
-  });
+  }));
 };
 
 Crowi.prototype.setupAppConfig = function() {
   return new Promise((resolve, reject) => {
     this.model('Config', require('../models/config')(this));
-    var Config = this.model('Config');
+    const Config = this.model('Config');
     Config.loadAllConfig((err, doc) => {
       if (err) {
         return reject();
@@ -204,15 +201,13 @@ Crowi.prototype.setupConfigManager = async function() {
 };
 
 Crowi.prototype.setupModels = function() {
-  var self = this
-    ;
-
-  return new Promise(function(resolve, reject) {
-    Object.keys(models).forEach(function(key) {
+  const self = this;
+  return new Promise(((resolve, reject) => {
+    Object.keys(models).forEach((key) => {
       self.model(key, models[key](self));
     });
     resolve();
-  });
+  }));
 };
 
 Crowi.prototype.getIo = function() {
@@ -220,11 +215,10 @@ Crowi.prototype.getIo = function() {
 };
 
 Crowi.prototype.scanRuntimeVersions = function() {
-  var self = this
-    , check = require('check-node-version')
-    ;
+  const self = this;
 
 
+  const check = require('check-node-version');
   return new Promise((resolve, reject) => {
     check((err, result) => {
       if (err) {
@@ -289,13 +283,11 @@ Crowi.prototype.setupPassport = function() {
 };
 
 Crowi.prototype.setupSearcher = function() {
-  var self = this;
-  var searcherUri = this.env.ELASTICSEARCH_URI
+  const self = this;
+  const searcherUri = this.env.ELASTICSEARCH_URI
     || this.env.BONSAI_URL
-    || null
-    ;
-
-  return new Promise(function(resolve, reject) {
+    || null;
+  return new Promise(((resolve, reject) => {
     if (searcherUri) {
       try {
         self.searcher = new (require(path.join(self.libDir, 'util', 'search')))(self, searcherUri);
@@ -306,23 +298,23 @@ Crowi.prototype.setupSearcher = function() {
       }
     }
     resolve();
-  });
+  }));
 };
 
 Crowi.prototype.setupMailer = function() {
-  var self = this;
-  return new Promise(function(resolve, reject) {
+  const self = this;
+  return new Promise(((resolve, reject) => {
     self.mailer = require('../util/mailer')(self);
     resolve();
-  });
+  }));
 };
 
 Crowi.prototype.setupSlack = function() {
-  var self = this;
-  var config = this.getConfig();
-  var Config = this.model('Config');
+  const self = this;
+  const config = this.getConfig();
+  const Config = this.model('Config');
 
-  return new Promise(function(resolve, reject) {
+  return new Promise(((resolve, reject) => {
     if (!Config.hasSlackConfig(config)) {
       self.slack = {};
     }
@@ -331,11 +323,11 @@ Crowi.prototype.setupSlack = function() {
     }
 
     resolve();
-  });
+  }));
 };
 
 Crowi.prototype.setupCsrf = function() {
-  var Tokens = require('csrf');
+  const Tokens = require('csrf');
   this.tokens = new Tokens();
 
   return Promise.resolve();
@@ -368,7 +360,7 @@ Crowi.prototype.start = async function() {
 
   // setup WebSocket
   const io = require('socket.io')(serverListening);
-  io.sockets.on('connection', function(socket) {
+  io.sockets.on('connection', (socket) => {
   });
   this.io = io;
 
@@ -379,18 +371,18 @@ Crowi.prototype.start = async function() {
 };
 
 Crowi.prototype.buildServer = function() {
-  var express = require('express')()
-    , env = this.node_env
-    ;
+  const express = require('express')();
+  const env = this.node_env;
+
   require('./express-init')(this, express);
 
   // import plugins
-  var Config = this.model('Config');
-  var isEnabledPlugins = Config.isEnabledPlugins(this.config);
+  const Config = this.model('Config');
+  const isEnabledPlugins = Config.isEnabledPlugins(this.config);
   if (isEnabledPlugins) {
     debug('Plugins are enabled');
-    var PluginService = require('../plugins/plugin.service');
-    var pluginService = new PluginService(this, express);
+    const PluginService = require('../plugins/plugin.service');
+    const pluginService = new PluginService(this, express);
     pluginService.autoDetectAndLoadPlugins();
 
     if (env == 'development') {

+ 3 - 3
src/server/events/page.js

@@ -1,6 +1,6 @@
-var debug = require('debug')('growi:events:page');
-var util = require('util');
-var events = require('events');
+const debug = require('debug')('growi:events:page');
+const util = require('util');
+const events = require('events');
 
 function PageEvent(crowi) {
   this.crowi = crowi;

+ 3 - 5
src/server/form/admin/app.js

@@ -1,12 +1,10 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field;
+const field = form.field;
 
 module.exports = form(
   field('settingForm[app:title]').trim(),
   field('settingForm[app:confidential]'),
   field('settingForm[app:globalLang]'),
-  field('settingForm[app:fileUpload]').trim().toBooleanStrict()
+  field('settingForm[app:fileUpload]').trim().toBooleanStrict(),
 );
-

+ 3 - 5
src/server/form/admin/aws.js

@@ -1,12 +1,10 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field;
+const field = form.field;
 
 module.exports = form(
   field('settingForm[aws:region]', 'リージョン').trim().is(/^[a-z]+-[a-z]+-\d+$/, 'リージョンには、AWSリージョン名を入力してください。 例: ap-northeast-1'),
   field('settingForm[aws:bucket]', 'バケット名').trim(),
   field('settingForm[aws:accessKeyId]', 'Access Key Id').trim().is(/^[\da-zA-Z]+$/),
-  field('settingForm[aws:secretAccessKey]', 'Secret Access Key').trim()
+  field('settingForm[aws:secretAccessKey]', 'Secret Access Key').trim(),
 );
-

+ 3 - 5
src/server/form/admin/custombehavior.js

@@ -1,9 +1,7 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field
-  ;
+const field = form.field;
 
 module.exports = form(
-  field('settingForm[customize:behavior]')
+  field('settingForm[customize:behavior]'),
 );

+ 3 - 5
src/server/form/admin/customcss.js

@@ -1,9 +1,7 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field
-  ;
+const field = form.field;
 
 module.exports = form(
-  field('settingForm[customize:css]')
+  field('settingForm[customize:css]'),
 );

+ 3 - 5
src/server/form/admin/customfeatures.js

@@ -1,12 +1,10 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field;
+const field = form.field;
 
 module.exports = form(
   field('settingForm[customize:isEnabledTimeline]').trim().toBooleanStrict(),
   field('settingForm[customize:isSavedStatesOfTabChanges]').trim().toBooleanStrict(),
   field('settingForm[customize:isEnabledAttachTitleHeader]').trim().toBooleanStrict(),
-  field('settingForm[customize:showRecentCreatedNumber]').trim().toInt()
+  field('settingForm[customize:showRecentCreatedNumber]').trim().toInt(),
 );
-

+ 3 - 5
src/server/form/admin/customheader.js

@@ -1,9 +1,7 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field
-  ;
+const field = form.field;
 
 module.exports = form(
-  field('settingForm[customize:header]')
+  field('settingForm[customize:header]'),
 );

+ 3 - 5
src/server/form/admin/customhighlightJsStyle.js

@@ -1,10 +1,8 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field
-  ;
+const field = form.field;
 
 module.exports = form(
   field('settingForm[customize:highlightJsStyle]'),
-  field('settingForm[customize:highlightJsStyleBorder]').trim().toBooleanStrict()
+  field('settingForm[customize:highlightJsStyleBorder]').trim().toBooleanStrict(),
 );

+ 3 - 5
src/server/form/admin/customlayout.js

@@ -1,10 +1,8 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field
-  ;
+const field = form.field;
 
 module.exports = form(
   field('settingForm[customize:layout]'),
-  field('settingForm[customize:theme]')
+  field('settingForm[customize:theme]'),
 );

+ 3 - 5
src/server/form/admin/customscript.js

@@ -1,9 +1,7 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field
-  ;
+const field = form.field;
 
 module.exports = form(
-  field('settingForm[customize:script]')
+  field('settingForm[customize:script]'),
 );

+ 3 - 5
src/server/form/admin/customtheme.js

@@ -1,9 +1,7 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field
-  ;
+const field = form.field;
 
 module.exports = form(
-  field('settingForm[customize:theme]')
+  field('settingForm[customize:theme]'),
 );

+ 3 - 5
src/server/form/admin/customtitle.js

@@ -1,9 +1,7 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field
-  ;
+const field = form.field;
 
 module.exports = form(
-  field('settingForm[customize:title]')
+  field('settingForm[customize:title]'),
 );

+ 2 - 4
src/server/form/admin/importerEsa.js

@@ -1,10 +1,8 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field;
+const field = form.field;
 
 module.exports = form(
   field('settingForm[importer:esa:access_token]').required(),
   field('settingForm[importer:esa:team_name]').required(),
 );
-

+ 2 - 4
src/server/form/admin/importerQiita.js

@@ -1,10 +1,8 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field;
+const field = form.field;
 
 module.exports = form(
   field('settingForm[importer:qiita:access_token]').required(),
   field('settingForm[importer:qiita:team_name]').required(),
 );
-

+ 3 - 6
src/server/form/admin/mail.js

@@ -1,14 +1,11 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field;
+const field = form.field;
 
 module.exports = form(
   field('settingForm[mail:from]', 'メールFrom').trim(),
   field('settingForm[mail:smtpHost]', 'SMTPホスト').trim(),
   field('settingForm[mail:smtpPort]', 'SMTPポート').trim().toInt(),
   field('settingForm[mail:smtpUser]', 'SMTPユーザー').trim(),
-  field('settingForm[mail:smtpPassword]', 'SMTPパスワード').trim()
+  field('settingForm[mail:smtpPassword]', 'SMTPパスワード').trim(),
 );
-
-

+ 3 - 5
src/server/form/admin/markdown.js

@@ -1,10 +1,8 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field;
+const field = form.field;
 
 module.exports = form(
   field('markdownSetting[markdown:isEnabledLinebreaks]').trim().toBooleanStrict(),
-  field('markdownSetting[markdown:isEnabledLinebreaksInComments]').trim().toBooleanStrict()
+  field('markdownSetting[markdown:isEnabledLinebreaksInComments]').trim().toBooleanStrict(),
 );
-

+ 3 - 4
src/server/form/admin/markdownPresentation.js

@@ -1,9 +1,8 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field;
+const field = form.field;
 
 module.exports = form(
   field('markdownSetting[markdown:presentation:pageBreakSeparator]').trim().toInt(),
-  field('markdownSetting[markdown:presentation:pageBreakCustomSeparator]').trim()
+  field('markdownSetting[markdown:presentation:pageBreakCustomSeparator]').trim(),
 );

+ 3 - 4
src/server/form/admin/markdownXss.js

@@ -1,11 +1,10 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field;
+const field = form.field;
 
 module.exports = form(
   field('markdownSetting[markdown:xss:isEnabledPrevention]').trim().toBooleanStrict(),
   field('markdownSetting[markdown:xss:option]').trim().toInt(),
   field('markdownSetting[markdown:xss:tagWhiteList]').trim(),
-  field('markdownSetting[markdown:xss:attrWhiteList]').trim()
+  field('markdownSetting[markdown:xss:attrWhiteList]').trim(),
 );

+ 1 - 3
src/server/form/admin/notificationGlobal.js

@@ -1,6 +1,5 @@
-'use strict';
-
 const form = require('express-form');
+
 const field = form.field;
 
 module.exports = form(
@@ -16,4 +15,3 @@ module.exports = form(
   field('notificationGlobal[triggerEvent:pageLike]').trim(),
   field('notificationGlobal[triggerEvent:comment]').trim(),
 );
-

+ 3 - 5
src/server/form/admin/plugin.js

@@ -1,9 +1,7 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field;
+const field = form.field;
 
 module.exports = form(
-  field('settingForm[plugin:isEnabledPlugins]').trim().toBooleanStrict()
+  field('settingForm[plugin:isEnabledPlugins]').trim().toBooleanStrict(),
 );
-

+ 1 - 2
src/server/form/admin/securityGeneral.js

@@ -1,6 +1,5 @@
-'use strict';
+const form = require('express-form');
 
-const form = require('express-form')
 const field = form.field;
 const stringToArray = require('../../util/formUtil').stringToArrayFilter;
 const normalizeCRLF = require('../../util/formUtil').normalizeCRLFFilter;

+ 3 - 5
src/server/form/admin/securityGoogle.js

@@ -1,10 +1,8 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field;
+const field = form.field;
 
 module.exports = form(
   field('settingForm[google:clientId]').trim().is(/^[\d\.a-z\-\.]+$/),
-  field('settingForm[google:clientSecret]').trim().is(/^[\da-zA-Z\-_]+$/)
+  field('settingForm[google:clientSecret]').trim().is(/^[\da-zA-Z\-_]+$/),
 );
-

+ 3 - 5
src/server/form/admin/securityMechanism.js

@@ -1,9 +1,7 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field;
+const field = form.field;
 
 module.exports = form(
-  field('settingForm[security:isEnabledPassport]').trim().toBooleanStrict()
+  field('settingForm[security:isEnabledPassport]').trim().toBooleanStrict(),
 );
-

+ 2 - 4
src/server/form/admin/securityPassportGitHub.js

@@ -1,8 +1,6 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field
-  ;
+const field = form.field;
 
 module.exports = form(
   field('settingForm[security:passport-github:isEnabled]').trim().toBooleanStrict().required(),

+ 2 - 4
src/server/form/admin/securityPassportGoogle.js

@@ -1,8 +1,6 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field
-  ;
+const field = form.field;
 
 module.exports = form(
   field('settingForm[security:passport-google:isEnabled]').trim().toBooleanStrict().required(),

+ 3 - 5
src/server/form/admin/securityPassportLdap.js

@@ -1,8 +1,6 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field
-  ;
+const field = form.field;
 
 module.exports = form(
   field('settingForm[security:passport-ldap:isEnabled]').trim().toBooleanStrict().required(),
@@ -21,5 +19,5 @@ module.exports = form(
   field('settingForm[security:passport-ldap:isSameUsernameTreatedAsIdenticalUser]').trim().toBooleanStrict(),
   field('settingForm[security:passport-ldap:groupSearchBase]'),
   field('settingForm[security:passport-ldap:groupSearchFilter]'),
-  field('settingForm[security:passport-ldap:groupDnProperty]')
+  field('settingForm[security:passport-ldap:groupDnProperty]'),
 );

+ 1 - 2
src/server/form/admin/securityPassportSaml.js

@@ -1,6 +1,5 @@
-'use strict';
-
 const form = require('express-form');
+
 const field = form.field;
 
 module.exports = form(

+ 2 - 4
src/server/form/admin/securityPassportTwitter.js

@@ -1,8 +1,6 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field
-  ;
+const field = form.field;
 
 module.exports = form(
   field('settingForm[security:passport-twitter:isEnabled]').trim().toBooleanStrict().required(),

+ 3 - 4
src/server/form/admin/siteUrl.js

@@ -1,8 +1,7 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field;
+const field = form.field;
 
 module.exports = form(
-  field('settingForm[app:siteUrl]').trim().isUrl()
+  field('settingForm[app:siteUrl]').trim().isUrl(),
 );

+ 3 - 5
src/server/form/admin/slackIwhSetting.js

@@ -1,10 +1,8 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field;
+const field = form.field;
 
 module.exports = form(
   field('slackIwhSetting[slack:incomingWebhookUrl]', 'Webhook URL'),
-  field('slackIwhSetting[slack:isIncomingWebhookPrioritized]', 'Prioritize Incoming Webhook than Slack App ').trim().toBooleanStrict()
+  field('slackIwhSetting[slack:isIncomingWebhookPrioritized]', 'Prioritize Incoming Webhook than Slack App ').trim().toBooleanStrict(),
 );
-

+ 3 - 4
src/server/form/admin/slackSetting.js

@@ -1,8 +1,7 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field;
+const field = form.field;
 
 module.exports = form(
-  field('slackSetting[slack:token]', 'token')
+  field('slackSetting[slack:token]', 'token'),
 );

+ 3 - 4
src/server/form/admin/userGroupCreate.js

@@ -1,8 +1,7 @@
-'use strict';
+const form = require('express-form');
 
-const form = require('express-form')
-  , field = form.field;
+const field = form.field;
 
 module.exports = form(
-  field('createGroupForm[userGroupName]', '新規グループ名').trim().required()
+  field('createGroupForm[userGroupName]', '新規グループ名').trim().required(),
 );

+ 3 - 4
src/server/form/admin/userInvite.js

@@ -1,9 +1,8 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field;
+const field = form.field;
 
 module.exports = form(
   field('inviteForm[emailList]', '招待メールアドレス').trim().required(),
-  field('inviteForm[sendEmail]').trim()
+  field('inviteForm[sendEmail]').trim(),
 );

+ 2 - 3
src/server/form/comment.js

@@ -1,7 +1,6 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field;
+const field = form.field;
 
 module.exports = form(
   field('commentForm.page_id').trim().required(),

+ 2 - 4
src/server/form/invited.js

@@ -1,11 +1,9 @@
-'use strict';
-
 const form = require('express-form');
+
 const field = form.field;
 
 module.exports = form(
   field('invitedForm.username').required().is(/^[\da-zA-Z\-_.]+$/),
   field('invitedForm.name').required(),
-  field('invitedForm.password').required().is(/^[\x20-\x7F]{6,}$/)
+  field('invitedForm.password').required().is(/^[\x20-\x7F]{6,}$/),
 );
-

+ 2 - 3
src/server/form/login.js

@@ -1,9 +1,8 @@
-'use strict';
-
 const form = require('express-form');
+
 const field = form.field;
 
 module.exports = form(
   field('loginForm.username').required(),
-  field('loginForm.password').required()
+  field('loginForm.password').required(),
 );

+ 3 - 5
src/server/form/me/apiToken.js

@@ -1,9 +1,7 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field;
+const field = form.field;
 
 module.exports = form(
-  field('apiTokenForm.confirm').required()
+  field('apiTokenForm.confirm').required(),
 );
-

+ 3 - 4
src/server/form/me/imagetype.js

@@ -1,8 +1,7 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field;
+const field = form.field;
 
 module.exports = form(
-  field('imagetypeForm.isGravatarEnabled').required()
+  field('imagetypeForm.isGravatarEnabled').required(),
 );

+ 2 - 3
src/server/form/me/password.js

@@ -1,10 +1,9 @@
-'use strict';
-
 const form = require('express-form');
+
 const field = form.field;
 
 module.exports = form(
   field('mePassword.oldPassword'),
   field('mePassword.newPassword').required().is(/^[\x20-\x7F]{6,}$/),
-  field('mePassword.newPasswordConfirm').required()
+  field('mePassword.newPasswordConfirm').required(),
 );

+ 3 - 4
src/server/form/me/user.js

@@ -1,11 +1,10 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field;
+const field = form.field;
 
 module.exports = form(
   field('userForm.name').trim().required(),
   field('userForm.email').trim().isEmail().required(),
   field('userForm.lang').required(),
-  field('userForm.isEmailPublished').trim().toBooleanStrict().required()
+  field('userForm.isEmailPublished').trim().toBooleanStrict().required(),
 );

+ 2 - 3
src/server/form/register.js

@@ -1,6 +1,5 @@
-'use strict';
-
 const form = require('express-form');
+
 const field = form.field;
 
 module.exports = form(
@@ -10,5 +9,5 @@ module.exports = form(
   field('registerForm.password').required().is(/^[\x20-\x7F]{6,}$/),
   field('registerForm.googleId'),
   field('registerForm.googleImage'),
-  field('registerForm[app:globalLang]')
+  field('registerForm[app:globalLang]'),
 );

+ 4 - 5
src/server/form/revision.js

@@ -1,16 +1,15 @@
-'use strict';
+const form = require('express-form');
 
-var form = require('express-form')
-  , field = form.field;
+const field = form.field;
 
 module.exports = form(
   field('pageForm.path').required(),
-  field('pageForm.body').required().custom(function(value) {
+  field('pageForm.body').required().custom((value) => {
     // see https://github.com/weseek/growi/issues/463
     return value.replace(/\r\n?/g, '\n');
   }),
   field('pageForm.currentRevision'),
   field('pageForm.grant').toInt().required(),
   field('pageForm.grantUserGroupId'),
-  field('pageForm.notify')
+  field('pageForm.notify'),
 );

+ 1 - 0
src/server/models/GlobalNotificationSetting.js

@@ -1,5 +1,6 @@
 const mongoose = require('mongoose');
 const GlobalNotificationSetting = require('./GlobalNotificationSetting/index');
+
 const GlobalNotificationSettingClass = GlobalNotificationSetting.class;
 const GlobalNotificationSettingSchema = GlobalNotificationSetting.schema;
 

+ 7 - 7
src/server/models/attachment.js

@@ -3,6 +3,7 @@ const logger = require('@alias/logger')('growi:models:attachment');
 const path = require('path');
 
 const mongoose = require('mongoose');
+
 const ObjectId = mongoose.Schema.Types.ObjectId;
 
 module.exports = function(crowi) {
@@ -20,8 +21,8 @@ module.exports = function(crowi) {
 
   attachmentSchema = new mongoose.Schema({
     page: { type: ObjectId, ref: 'Page', index: true },
-    creator: { type: ObjectId, ref: 'User', index: true  },
-    filePath: { type: String },   // DEPRECATED: remains for backward compatibility for v3.3.x or below
+    creator: { type: ObjectId, ref: 'User', index: true },
+    filePath: { type: String }, // DEPRECATED: remains for backward compatibility for v3.3.x or below
     fileName: { type: String, required: true },
     originalName: { type: String },
     fileFormat: { type: String, required: true },
@@ -46,7 +47,7 @@ module.exports = function(crowi) {
 
     const extname = path.extname(originalName);
     let fileName = generateFileHash(originalName);
-    if (extname.length > 1) {   // ignore if empty or '.' only
+    if (extname.length > 1) { // ignore if empty or '.' only
       fileName = `${fileName}${extname}`;
     }
 
@@ -68,12 +69,12 @@ module.exports = function(crowi) {
   };
 
   attachmentSchema.statics.removeAttachmentsByPageId = function(pageId) {
-    var Attachment = this;
+    const Attachment = this;
 
     return new Promise((resolve, reject) => {
-      Attachment.find({ page: pageId})
+      Attachment.find({ page: pageId })
       .then((attachments) => {
-        for (let attachment of attachments) {
+        for (const attachment of attachments) {
           Attachment.removeWithSubstanceById(attachment._id).then((res) => {
             // do nothing
           }).catch((err) => {
@@ -86,7 +87,6 @@ module.exports = function(crowi) {
         reject(err);
       });
     });
-
   };
 
   attachmentSchema.statics.removeWithSubstanceById = async function(id) {

+ 11 - 11
src/server/models/bookmark.js

@@ -10,9 +10,9 @@ module.exports = function(crowi) {
   bookmarkSchema = new mongoose.Schema({
     page: { type: ObjectId, ref: 'Page', index: true },
     user: { type: ObjectId, ref: 'User', index: true },
-    createdAt: { type: Date, default: Date.now() }
+    createdAt: { type: Date, default: Date.now() },
   });
-  bookmarkSchema.index({page: 1, user: 1}, {unique: true});
+  bookmarkSchema.index({ page: 1, user: 1 }, { unique: true });
 
   bookmarkSchema.statics.countByPageId = async function(pageId) {
     return await this.count({ page: pageId });
@@ -23,8 +23,8 @@ module.exports = function(crowi) {
     const User = crowi.model('User');
 
     return Bookmark.populate(bookmarks, [
-      {path: 'page'},
-      {path: 'lastUpdateUser', model: 'User', select: User.USER_PUBLIC_FIELDS},
+      { path: 'page' },
+      { path: 'lastUpdateUser', model: 'User', select: User.USER_PUBLIC_FIELDS },
     ]);
   };
 
@@ -32,15 +32,15 @@ module.exports = function(crowi) {
   bookmarkSchema.statics.findByPageIdAndUserId = function(pageId, userId) {
     const Bookmark = this;
 
-    return new Promise(function(resolve, reject) {
-      return Bookmark.findOne({ page: pageId, user: userId }, function(err, doc) {
+    return new Promise(((resolve, reject) => {
+      return Bookmark.findOne({ page: pageId, user: userId }, (err, doc) => {
         if (err) {
           return reject(err);
         }
 
         return resolve(doc);
       });
-    });
+    }));
   };
 
   /**
@@ -60,13 +60,13 @@ module.exports = function(crowi) {
     const offset = option.offset || 0;
     const populatePage = option.populatePage || false;
 
-    return new Promise(function(resolve, reject) {
+    return new Promise(((resolve, reject) => {
       Bookmark
         .find({ user: user._id })
-        .sort({createdAt: -1})
+        .sort({ createdAt: -1 })
         .skip(offset)
         .limit(limit)
-        .exec(function(err, bookmarks) {
+        .exec((err, bookmarks) => {
           if (err) {
             return reject(err);
           }
@@ -77,7 +77,7 @@ module.exports = function(crowi) {
 
           return Bookmark.populatePage(bookmarks, requestUser).then(resolve);
         });
-    });
+    }));
   };
 
   bookmarkSchema.statics.add = async function(page, user) {

+ 31 - 33
src/server/models/comment.js

@@ -1,28 +1,26 @@
 module.exports = function(crowi) {
-  var debug = require('debug')('growi:models:comment')
-    , mongoose = require('mongoose')
-    , ObjectId = mongoose.Schema.Types.ObjectId
-    , USER_PUBLIC_FIELDS = '_id image isGravatarEnabled googleId name username email status createdAt' // TODO: どこか別の場所へ...
-    , commentSchema
-  ;
-
-  commentSchema = new mongoose.Schema({
+  const debug = require('debug')('growi:models:comment');
+  const mongoose = require('mongoose');
+  const ObjectId = mongoose.Schema.Types.ObjectId;
+  const USER_PUBLIC_FIELDS = '_id image isGravatarEnabled googleId name username email status createdAt';
+  // TODO: どこか別の場所へ...
+
+  const commentSchema = new mongoose.Schema({
     page: { type: ObjectId, ref: 'Page', index: true },
-    creator: { type: ObjectId, ref: 'User', index: true  },
+    creator: { type: ObjectId, ref: 'User', index: true },
     revision: { type: ObjectId, ref: 'Revision', index: true },
     comment: { type: String, required: true },
     commentPosition: { type: Number, default: -1 },
     createdAt: { type: Date, default: Date.now },
-    isMarkdown: { type: Boolean, default: false}
+    isMarkdown: { type: Boolean, default: false },
   });
 
   commentSchema.statics.create = function(pageId, creatorId, revisionId, comment, position, isMarkdown) {
-    var Comment = this,
-      commentPosition = position || -1;
-
+    const Comment = this;
+    const commentPosition = position || -1;
 
-    return new Promise(function(resolve, reject) {
-      var newComment = new Comment();
+    return new Promise(((resolve, reject) => {
+      const newComment = new Comment();
 
       newComment.page = pageId;
       newComment.creator = creatorId;
@@ -31,7 +29,7 @@ module.exports = function(crowi) {
       newComment.commentPosition = position;
       newComment.isMarkdown = isMarkdown || false;
 
-      newComment.save(function(err, data) {
+      newComment.save((err, data) => {
         if (err) {
           debug('Error on saving comment.', err);
           return reject(err);
@@ -39,57 +37,57 @@ module.exports = function(crowi) {
         debug('Comment saved.', data);
         return resolve(data);
       });
-    });
+    }));
   };
 
   commentSchema.statics.getCommentsByPageId = function(id) {
-    return this.find({page: id}).sort({'createdAt': -1});
+    return this.find({ page: id }).sort({ createdAt: -1 });
   };
 
   commentSchema.statics.getCommentsByRevisionId = function(id) {
-    return this.find({revision: id}).sort({'createdAt': -1});
+    return this.find({ revision: id }).sort({ createdAt: -1 });
   };
 
   commentSchema.statics.countCommentByPageId = function(page) {
-    var self = this;
+    const self = this;
 
-    return new Promise(function(resolve, reject) {
-      self.count({page: page}, function(err, data) {
+    return new Promise(((resolve, reject) => {
+      self.count({ page }, (err, data) => {
         if (err) {
           return reject(err);
         }
 
         return resolve(data);
       });
-    });
+    }));
   };
 
   commentSchema.statics.removeCommentsByPageId = function(pageId) {
-    var Comment = this;
+    const Comment = this;
 
-    return new Promise(function(resolve, reject) {
-      Comment.remove({page: pageId}, function(err, done) {
+    return new Promise(((resolve, reject) => {
+      Comment.remove({ page: pageId }, (err, done) => {
         if (err) {
           return reject(err);
         }
 
         resolve(done);
       });
-    });
+    }));
   };
 
   /**
    * post save hook
    */
-  commentSchema.post('save', function(savedComment) {
-    var Page = crowi.model('Page')
-      , Comment = crowi.model('Comment')
-    ;
+  commentSchema.post('save', (savedComment) => {
+    const Page = crowi.model('Page');
+
 
+    const Comment = crowi.model('Comment');
     Page.updateCommentCount(savedComment.page)
-    .then(function(page) {
+    .then((page) => {
       debug('CommentCount Updated', page);
-    }).catch(function() {
+    }).catch(() => {
     });
   });
 

+ 53 - 54
src/server/models/config.js

@@ -1,16 +1,14 @@
 module.exports = function(crowi) {
-  const mongoose = require('mongoose')
-    , debug = require('debug')('growi:models:config')
-    , uglifycss = require('uglifycss')
-    , recommendedXssWhiteList = require('@commons/service/xss/recommendedXssWhiteList')
+  const mongoose = require('mongoose');
+  const debug = require('debug')('growi:models:config');
+  const uglifycss = require('uglifycss');
+  const recommendedXssWhiteList = require('@commons/service/xss/recommendedXssWhiteList');
 
-    , SECURITY_RESTRICT_GUEST_MODE_DENY = 'Deny'
-    , SECURITY_RESTRICT_GUEST_MODE_READONLY = 'Readonly'
-
-    , SECURITY_REGISTRATION_MODE_OPEN = 'Open'
-    , SECURITY_REGISTRATION_MODE_RESTRICTED = 'Resricted'
-    , SECURITY_REGISTRATION_MODE_CLOSED = 'Closed'
-  ;
+  const SECURITY_RESTRICT_GUEST_MODE_DENY = 'Deny';
+  const SECURITY_RESTRICT_GUEST_MODE_READONLY = 'Readonly';
+  const SECURITY_REGISTRATION_MODE_OPEN = 'Open';
+  const SECURITY_REGISTRATION_MODE_RESTRICTED = 'Resricted';
+  const SECURITY_REGISTRATION_MODE_CLOSED = 'Closed';
 
   let configSchema;
   let Config;
@@ -18,7 +16,7 @@ module.exports = function(crowi) {
   configSchema = new mongoose.Schema({
     ns: { type: String, required: true, index: true },
     key: { type: String, required: true, index: true },
-    value: { type: String, required: true }
+    value: { type: String, required: true },
   });
 
   function validateCrowi() {
@@ -31,7 +29,7 @@ module.exports = function(crowi) {
    * default values when GROWI is cleanly installed
    */
   function getArrayForInstalling() {
-    let config = getDefaultCrowiConfigs();
+    const config = getDefaultCrowiConfigs();
 
     // overwrite
     config['app:fileUpload'] = true;
@@ -49,7 +47,7 @@ module.exports = function(crowi) {
   function getDefaultCrowiConfigs() {
     /* eslint-disable key-spacing */
     return {
-      //'app:installed'     : "0.0.0",
+      // 'app:installed'     : "0.0.0",
       'app:confidential'  : '',
 
       'app:fileUpload'    : false,
@@ -167,18 +165,18 @@ module.exports = function(crowi) {
   };
 
   configSchema.statics.getRestrictGuestModeLabels = function() {
-    var labels = {};
-    labels[SECURITY_RESTRICT_GUEST_MODE_DENY]     = 'security_setting.guest_mode.deny';
+    const labels = {};
+    labels[SECURITY_RESTRICT_GUEST_MODE_DENY] = 'security_setting.guest_mode.deny';
     labels[SECURITY_RESTRICT_GUEST_MODE_READONLY] = 'security_setting.guest_mode.readonly';
 
     return labels;
   };
 
   configSchema.statics.getRegistrationModeLabels = function() {
-    var labels = {};
-    labels[SECURITY_REGISTRATION_MODE_OPEN]       = 'security_setting.registration_mode.open';
+    const labels = {};
+    labels[SECURITY_REGISTRATION_MODE_OPEN] = 'security_setting.registration_mode.open';
     labels[SECURITY_REGISTRATION_MODE_RESTRICTED] = 'security_setting.registration_mode.restricted';
-    labels[SECURITY_REGISTRATION_MODE_CLOSED]     = 'security_setting.registration_mode.closed';
+    labels[SECURITY_REGISTRATION_MODE_CLOSED] = 'security_setting.registration_mode.closed';
 
     return labels;
   };
@@ -188,7 +186,7 @@ module.exports = function(crowi) {
 
     const originalConfig = crowi.getConfig();
     const newNSConfig = originalConfig[ns] || {};
-    Object.keys(config).forEach(function(key) {
+    Object.keys(config).forEach((key) => {
       if (config[key] || config[key] === '' || config[key] === false) {
         newNSConfig[key] = config[key];
       }
@@ -204,13 +202,12 @@ module.exports = function(crowi) {
 
   // Execute only once for installing application
   configSchema.statics.applicationInstall = function(callback) {
-    var Config = this;
-    Config.count({ ns: 'crowi' }, function(err, count) {
+    const Config = this;
+    Config.count({ ns: 'crowi' }, (err, count) => {
       if (count > 0) {
         return callback(new Error('Application already installed'), null);
       }
-      Config.updateNamespaceByArray('crowi', getArrayForInstalling(), function(err, configs) {
-
+      Config.updateNamespaceByArray('crowi', getArrayForInstalling(), (err, configs) => {
         Config.updateConfigCache('crowi', configs);
         return callback(err, configs);
       });
@@ -218,7 +215,7 @@ module.exports = function(crowi) {
   };
 
   configSchema.statics.setupConfigFormData = function(ns, config) {
-    var defaultConfig = {};
+    let defaultConfig = {};
 
     // set Default Settings
     if (ns === 'crowi') {
@@ -231,7 +228,7 @@ module.exports = function(crowi) {
     if (!defaultConfig[ns]) {
       defaultConfig[ns] = {};
     }
-    Object.keys(config[ns] || {}).forEach(function(key) {
+    Object.keys(config[ns] || {}).forEach((key) => {
       if (config[ns][key] !== undefined) {
         defaultConfig[key] = config[ns][key];
       }
@@ -241,21 +238,22 @@ module.exports = function(crowi) {
 
 
   configSchema.statics.updateNamespaceByArray = function(ns, configs, callback) {
-    var Config = this;
+    const Config = this;
     if (configs.length < 0) {
       return callback(new Error('Argument #1 is not array.'), null);
     }
 
-    Object.keys(configs).forEach(function(key) {
-      var value = configs[key];
+    Object.keys(configs).forEach((key) => {
+      const value = configs[key];
 
       Config.findOneAndUpdate(
-        { ns: ns, key: key },
-        { ns: ns, key: key, value: JSON.stringify(value) },
-        { upsert: true, },
-        function(err, config) {
+        { ns, key },
+        { ns, key, value: JSON.stringify(value) },
+        { upsert: true },
+        (err, config) => {
           debug('Config.findAndUpdate', err, config);
-        });
+        },
+      );
     });
 
     return callback(null, configs);
@@ -263,24 +261,26 @@ module.exports = function(crowi) {
 
   configSchema.statics.findOneAndUpdateByNsAndKey = async function(ns, key, value) {
     return this.findOneAndUpdate(
-      { ns: ns, key: key },
-      { ns: ns, key: key, value: JSON.stringify(value) },
-      { upsert: true, });
+      { ns, key },
+      { ns, key, value: JSON.stringify(value) },
+      { upsert: true },
+    );
   };
 
   configSchema.statics.getConfig = function(callback) {
   };
 
   configSchema.statics.loadAllConfig = function(callback) {
-    var Config = this
-      , config = {};
+    const Config = this;
+
+
+    const config = {};
     config.crowi = {}; // crowi namespace
 
     Config.find()
-      .sort({ns: 1, key: 1})
-      .exec(function(err, doc) {
-
-        doc.forEach(function(el) {
+      .sort({ ns: 1, key: 1 })
+      .exec((err, doc) => {
+        doc.forEach((el) => {
           if (!config[el.ns]) {
             config[el.ns] = {};
           }
@@ -341,10 +341,10 @@ module.exports = function(crowi) {
     const method = process.env.FILE_UPLOAD || 'aws';
 
     if (method == 'aws' && (
-      !config.crowi['aws:accessKeyId'] ||
-        !config.crowi['aws:secretAccessKey'] ||
-        !config.crowi['aws:region'] ||
-        !config.crowi['aws:bucket'])) {
+      !config.crowi['aws:accessKeyId']
+        || !config.crowi['aws:secretAccessKey']
+        || !config.crowi['aws:region']
+        || !config.crowi['aws:bucket'])) {
       return false;
     }
 
@@ -391,7 +391,7 @@ module.exports = function(crowi) {
   };
   configSchema.statics.isPublicWikiOnly = function(config) {
     const publicWikiOnly = process.env.PUBLIC_WIKI_ONLY;
-    if ( publicWikiOnly === 'true' || publicWikiOnly == 1) {
+    if (publicWikiOnly === 'true' || publicWikiOnly == 1) {
       return true;
     }
     return false;
@@ -438,7 +438,6 @@ module.exports = function(crowi) {
     else {
       return [];
     }
-
   };
 
   configSchema.statics.attrWhiteList = function(config) {
@@ -579,14 +578,14 @@ module.exports = function(crowi) {
     if (!config.notification) {
       return false;
     }
-    return (config.notification['slack:incomingWebhookUrl'] ? true : false);
+    return (!!config.notification['slack:incomingWebhookUrl']);
   };
 
   configSchema.statics.isIncomingWebhookPrioritized = function(config) {
     if (!config.notification) {
       return false;
     }
-    return (config.notification['slack:isIncomingWebhookPrioritized'] ? true : false);
+    return (!!config.notification['slack:isIncomingWebhookPrioritized']);
   };
 
   configSchema.statics.hasSlackToken = function(config) {
@@ -594,7 +593,7 @@ module.exports = function(crowi) {
       return false;
     }
 
-    return (config.notification['slack:token'] ? true : false);
+    return (!!config.notification['slack:token']);
   };
 
   configSchema.statics.getLocalconfig = function(config) {
@@ -663,9 +662,9 @@ module.exports = function(crowi) {
   */
 
   Config = mongoose.model('Config', configSchema);
-  Config.SECURITY_REGISTRATION_MODE_OPEN       = SECURITY_REGISTRATION_MODE_OPEN;
+  Config.SECURITY_REGISTRATION_MODE_OPEN = SECURITY_REGISTRATION_MODE_OPEN;
   Config.SECURITY_REGISTRATION_MODE_RESTRICTED = SECURITY_REGISTRATION_MODE_RESTRICTED;
-  Config.SECURITY_REGISTRATION_MODE_CLOSED     = SECURITY_REGISTRATION_MODE_CLOSED;
+  Config.SECURITY_REGISTRATION_MODE_CLOSED = SECURITY_REGISTRATION_MODE_CLOSED;
 
 
   return Config;

+ 10 - 13
src/server/models/external-account.js

@@ -2,6 +2,7 @@ const debug = require('debug')('growi:models:external-account');
 const mongoose = require('mongoose');
 const mongoosePaginate = require('mongoose-paginate');
 const uniqueValidator = require('mongoose-unique-validator');
+
 const ObjectId = mongoose.Schema.Types.ObjectId;
 
 /*
@@ -14,7 +15,7 @@ const schema = new mongoose.Schema({
   createdAt: { type: Date, default: Date.now, required: true },
 });
 // compound index
-schema.index({ providerType: 1, accountId: 1}, { unique: true });
+schema.index({ providerType: 1, accountId: 1 }, { unique: true });
 // apply plugins
 schema.plugin(mongoosePaginate);
 schema.plugin(uniqueValidator);
@@ -25,7 +26,6 @@ schema.plugin(uniqueValidator);
  * @class ExternalAccount
  */
 class ExternalAccount {
-
   /**
    * limit items num for pagination
    *
@@ -73,9 +73,8 @@ class ExternalAccount {
    * @memberof ExternalAccount
    */
   static findOrRegister(providerType, accountId, usernameToBeRegistered, nameToBeRegistered, mailToBeRegistered, isSameUsernameTreatedAsIdenticalUser, isSameEmailTreatedAsIdenticalUser) {
-
     return this.findOne({ providerType, accountId })
-      .then(account => {
+      .then((account) => {
         // ExternalAccount is found
         if (account != null) {
           debug(`ExternalAccount '${accountId}' is found `, account);
@@ -84,20 +83,20 @@ class ExternalAccount {
 
         const User = ExternalAccount.crowi.model('User');
 
-        let promise = User.findOne({username: usernameToBeRegistered});
+        let promise = User.findOne({ username: usernameToBeRegistered });
         if (isSameUsernameTreatedAsIdenticalUser && isSameEmailTreatedAsIdenticalUser) {
           promise = promise
-            .then(user => {
-              if (user == null) { return User.findOne({email: mailToBeRegistered}) }
+            .then((user) => {
+              if (user == null) { return User.findOne({ email: mailToBeRegistered }) }
               return user;
             });
         }
         else if (isSameEmailTreatedAsIdenticalUser) {
-          promise = User.findOne({email: mailToBeRegistered});
+          promise = User.findOne({ email: mailToBeRegistered });
         }
 
         return promise
-          .then(user => {
+          .then((user) => {
             // when the User that have the same `username` exists
             if (user != null) {
               throw new DuplicatedUsernameException(`User '${usernameToBeRegistered}' already exists`, user);
@@ -110,10 +109,9 @@ class ExternalAccount {
             debug(`ExternalAccount '${accountId}' is not found, it is going to be registered.`);
             return User.createUser(nameToBeRegistered, usernameToBeRegistered, mailToBeRegistered, undefined, undefined, User.STATUS_ACTIVE);
           })
-          .then(newUser => {
+          .then((newUser) => {
             return this.associate(providerType, accountId, newUser);
           });
-
       });
   }
 
@@ -142,7 +140,7 @@ class ExternalAccount {
     const query = {};
     const options = Object.assign({ populate: 'user' }, opts);
     if (options.sort == null) {
-      options.sort = {accountId: 1, createdAt: 1};
+      options.sort = { accountId: 1, createdAt: 1 };
     }
     if (options.limit == null) {
       options.limit = ExternalAccount.DEFAULT_LIMIT;
@@ -153,7 +151,6 @@ class ExternalAccount {
         debug('Error on pagination:', err);
       });
   }
-
 }
 
 /**

+ 0 - 2
src/server/models/index.js

@@ -1,5 +1,3 @@
-'use strict';
-
 module.exports = {
   Page: require('./page'),
   PageGroupRelation: require('./page-group-relation'),