Yuki Takei 8 лет назад
Родитель
Сommit
9c15b1cf84

+ 1 - 1
config/env.dev.js

@@ -2,7 +2,7 @@ module.exports = {
   NODE_ENV: 'development',
   NODE_ENV: 'development',
   FILE_UPLOAD: 'local',
   FILE_UPLOAD: 'local',
   // MATHJAX: 1,
   // MATHJAX: 1,
-  // ELASTICSEARCH_URI: 'http://localhost:9200/growi',
+  ELASTICSEARCH_URI: 'http://localhost:9200/growi',
   PLUGIN_NAMES_TOBE_LOADED: [
   PLUGIN_NAMES_TOBE_LOADED: [
     // 'growi-plugin-lsx',
     // 'growi-plugin-lsx',
     // 'growi-plugin-pukiwiki-like-linker',
     // 'growi-plugin-pukiwiki-like-linker',

+ 3 - 1
lib/routes/index.js

@@ -24,6 +24,8 @@ module.exports = function(crowi, app) {
     , Config    = crowi.model('Config')
     , Config    = crowi.model('Config')
     ;
     ;
 
 
+  /* eslint-disable comma-spacing */
+
   app.get('/'                        , middleware.applicationInstalled(), loginRequired(crowi, app, false) , page.pageListShow);
   app.get('/'                        , middleware.applicationInstalled(), loginRequired(crowi, app, false) , page.pageListShow);
 
 
   app.get('/installer'               , middleware.applicationNotInstalled() , middleware.checkSearchIndicesGenerated(crowi, app) , installer.index);
   app.get('/installer'               , middleware.applicationNotInstalled() , middleware.checkSearchIndicesGenerated(crowi, app) , installer.index);
@@ -119,7 +121,7 @@ module.exports = function(crowi, app) {
   app.post('/_api/admin/user-group/:userGroupId/picture/upload', loginRequired(crowi, app), uploads.single('userGroupPicture'), admin.userGroup.uploadGroupPicture);
   app.post('/_api/admin/user-group/:userGroupId/picture/upload', loginRequired(crowi, app), uploads.single('userGroupPicture'), admin.userGroup.uploadGroupPicture);
 
 
   // user-group-relations admin
   // user-group-relations admin
-  app.post('/admin/user-group-relation/create', loginRequired(crowi, app), middleware.adminRequired(), csrf, admin.userGroupRelation.create)
+  app.post('/admin/user-group-relation/create', loginRequired(crowi, app), middleware.adminRequired(), csrf, admin.userGroupRelation.create);
   app.post('/admin/user-group-relation/:name/remove-relation/:relationId', loginRequired(crowi, app), middleware.adminRequired(), csrf, admin.userGroupRelation.remove)
   app.post('/admin/user-group-relation/:name/remove-relation/:relationId', loginRequired(crowi, app), middleware.adminRequired(), csrf, admin.userGroupRelation.remove)
 
 
   app.get('/me'                       , loginRequired(crowi, app) , me.index);
   app.get('/me'                       , loginRequired(crowi, app) , me.index);

+ 8 - 12
lib/routes/login-passport.js

@@ -73,7 +73,7 @@ module.exports = function(crowi, app) {
     const loginForm = req.body.loginForm;
     const loginForm = req.body.loginForm;
 
 
     if (!req.form.isValid) {
     if (!req.form.isValid) {
-      debug("invalid form");
+      debug('invalid form');
       return res.render('login', {
       return res.render('login', {
       });
       });
     }
     }
@@ -94,7 +94,7 @@ module.exports = function(crowi, app) {
       }
       }
 
 
       // authentication failure
       // authentication failure
-      if (!ldapAccountInfo) { return next(); }
+      if (!ldapAccountInfo) { return next() }
       // check groups
       // check groups
       if (!isValidLdapUserByGroupFilter(ldapAccountInfo)) {
       if (!isValidLdapUserByGroupFilter(ldapAccountInfo)) {
         return loginFailure(req, res, next);
         return loginFailure(req, res, next);
@@ -130,7 +130,7 @@ module.exports = function(crowi, app) {
         .then((user) => {
         .then((user) => {
           // login
           // login
           req.logIn(user, (err) => {
           req.logIn(user, (err) => {
-            if (err) { return next(); }
+            if (err) { return next() }
             else {
             else {
               return loginSuccess(req, res, user);
               return loginSuccess(req, res, user);
             }
             }
@@ -147,7 +147,7 @@ module.exports = function(crowi, app) {
         });
         });
 
 
     })(req, res, next);
     })(req, res, next);
-  }
+  };
 
 
   /**
   /**
    * middleware that test credentials with LdapStrategy
    * middleware that test credentials with LdapStrategy
@@ -164,8 +164,6 @@ module.exports = function(crowi, app) {
       });
       });
     }
     }
 
 
-    const loginForm = req.body.loginForm;
-
     passport.authenticate('ldapauth', (err, user, info) => {
     passport.authenticate('ldapauth', (err, user, info) => {
       if (res.headersSent) {  // dirty hack -- 2017.09.25
       if (res.headersSent) {  // dirty hack -- 2017.09.25
         return;               // cz: somehow passport.authenticate called twice when ECONNREFUSED error occurred
         return;               // cz: somehow passport.authenticate called twice when ECONNREFUSED error occurred
@@ -198,7 +196,7 @@ module.exports = function(crowi, app) {
         });
         });
       }
       }
     })(req, res, () => {});
     })(req, res, () => {});
-  }
+  };
 
 
   /**
   /**
    * middleware that login with LocalStrategy
    * middleware that login with LocalStrategy
@@ -207,8 +205,6 @@ module.exports = function(crowi, app) {
    * @param {*} next
    * @param {*} next
    */
    */
   const loginWithLocal = (req, res, next) => {
   const loginWithLocal = (req, res, next) => {
-    const loginForm = req.body.loginForm;
-
     if (!req.form.isValid) {
     if (!req.form.isValid) {
       return res.render('login', {
       return res.render('login', {
       });
       });
@@ -224,15 +220,15 @@ module.exports = function(crowi, app) {
         req.flash('warningMessage', 'Database Server Error occured.');
         req.flash('warningMessage', 'Database Server Error occured.');
         return next(); // pass and the flash message is displayed when all of authentications are failed.
         return next(); // pass and the flash message is displayed when all of authentications are failed.
       }
       }
-      if (!user) { return next(); }
+      if (!user) { return next() }
       req.logIn(user, (err) => {
       req.logIn(user, (err) => {
-        if (err) { return next(); }
+        if (err) { return next() }
         else {
         else {
           return loginSuccess(req, res, user);
           return loginSuccess(req, res, user);
         }
         }
       });
       });
     })(req, res, next);
     })(req, res, next);
-  }
+  };
 
 
   return {
   return {
     loginFailure,
     loginFailure,

+ 45 - 39
lib/routes/login.js

@@ -1,26 +1,22 @@
 module.exports = function(crowi, app) {
 module.exports = function(crowi, app) {
   'use strict';
   'use strict';
 
 
-  var googleapis = require('googleapis')
-    , debug = require('debug')('growi:routes:login')
+  var debug = require('debug')('growi:routes:login')
     , async    = require('async')
     , async    = require('async')
-    , passport = require('passport')
     , config = crowi.getConfig()
     , config = crowi.getConfig()
     , mailer = crowi.getMailer()
     , mailer = crowi.getMailer()
-    , Page = crowi.model('Page')
     , User = crowi.model('User')
     , User = crowi.model('User')
     , Config = crowi.model('Config')
     , Config = crowi.model('Config')
-    , Revision = crowi.model('Revision')
     , actions = {};
     , actions = {};
 
 
 
 
   var clearGoogleSession = function(req) {
   var clearGoogleSession = function(req) {
-      req.session.googleAuthCode
-        = req.session.googleId
-        = req.session.googleEmail
-        = req.session.googleName
-        = req.session.googleImage
-        = null;
+    req.session.googleAuthCode
+      = req.session.googleId
+      = req.session.googleEmail
+      = req.session.googleName
+      = req.session.googleImage
+      = null;
   };
   };
   var loginSuccess = function(req, res, userData) {
   var loginSuccess = function(req, res, userData) {
     req.user = req.session.user = userData;
     req.user = req.session.user = userData;
@@ -43,7 +39,8 @@ module.exports = function(crowi, app) {
     if (jumpTo) {
     if (jumpTo) {
       req.session.jumpTo = null;
       req.session.jumpTo = null;
       return res.redirect(jumpTo);
       return res.redirect(jumpTo);
-    } else {
+    }
+    else {
       return res.redirect('/');
       return res.redirect('/');
     }
     }
   };
   };
@@ -70,9 +67,9 @@ module.exports = function(crowi, app) {
 
 
     if (reason === 'suspended') {
     if (reason === 'suspended') {
       reasonMessage = 'This account is suspended.';
       reasonMessage = 'This account is suspended.';
-    } else if (reason === 'registered') {
+    }
+    else if (reason === 'registered') {
       reasonMessage = 'Wait for approved by administrators.';
       reasonMessage = 'Wait for approved by administrators.';
-    } else {
     }
     }
 
 
     return res.render('login/error', {
     return res.render('login/error', {
@@ -90,14 +87,15 @@ module.exports = function(crowi, app) {
 
 
       // find user
       // find user
       User.findUserByUsernameOrEmail(username, password, (err, user) => {
       User.findUserByUsernameOrEmail(username, password, (err, user) => {
-        if (err) { return loginFailure(req, res); }
+        if (err) { return loginFailure(req, res) }
         // check existence and password
         // check existence and password
         if (!user || !user.isPasswordValid(password)) {
         if (!user || !user.isPasswordValid(password)) {
           return loginFailure(req, res);
           return loginFailure(req, res);
         }
         }
         return loginSuccess(req, res, user);
         return loginSuccess(req, res, user);
       });
       });
-    } else { // method GET
+    }
+    else { // method GET
       if (req.form) {
       if (req.form) {
         debug(req.form.errors);
         debug(req.form.errors);
       }
       }
@@ -119,7 +117,8 @@ module.exports = function(crowi, app) {
         req.session.googleCallbackAction = '/login/google';
         req.session.googleCallbackAction = '/login/google';
         return res.redirect(redirectUrl);
         return res.redirect(redirectUrl);
       });
       });
-    } else {
+    }
+    else {
       googleAuth.handleCallback(req, function(err, tokenInfo) {
       googleAuth.handleCallback(req, function(err, tokenInfo) {
         debug('handleCallback', err, tokenInfo);
         debug('handleCallback', err, tokenInfo);
         if (err) {
         if (err) {
@@ -164,7 +163,7 @@ module.exports = function(crowi, app) {
       var googleImage = registerForm.googleImage || null;
       var googleImage = registerForm.googleImage || null;
 
 
       // email と username の unique チェックする
       // email と username の unique チェックする
-      User.isRegisterable(email, username, function (isRegisterable, errOn) {
+      User.isRegisterable(email, username, function(isRegisterable, errOn) {
         var isError = false;
         var isError = false;
         if (!User.isEmailValid(email)) {
         if (!User.isEmailValid(email)) {
           isError = true;
           isError = true;
@@ -190,7 +189,8 @@ module.exports = function(crowi, app) {
           if (err) {
           if (err) {
             req.flash('registerWarningMessage', 'Failed to register.');
             req.flash('registerWarningMessage', 'Failed to register.');
             return res.redirect('/register');
             return res.redirect('/register');
-          } else {
+          }
+          else {
 
 
             // 作成後、承認が必要なモードなら、管理者に通知する
             // 作成後、承認が必要なモードなら、管理者に通知する
             const appTitle = Config.appTitle(config);
             const appTitle = Config.appTitle(config);
@@ -201,20 +201,20 @@ module.exports = function(crowi, app) {
                   admins,
                   admins,
                   function(adminUser, next) {
                   function(adminUser, next) {
                     mailer.send({
                     mailer.send({
-                        to: adminUser.email,
-                        subject: '[' + appTitle + ':admin] A New User Created and Waiting for Activation',
-                        template: 'admin/userWaitingActivation.txt',
-                        vars: {
-                          createdUser: userData,
-                          adminUser: adminUser,
-                          url: config.crowi['app:url'],
-                          appTitle: appTitle,
-                        }
-                      },
-                      function (err, s) {
-                        debug('completed to send email: ', err, s);
-                        next();
+                      to: adminUser.email,
+                      subject: '[' + appTitle + ':admin] A New User Created and Waiting for Activation',
+                      template: 'admin/userWaitingActivation.txt',
+                      vars: {
+                        createdUser: userData,
+                        adminUser: adminUser,
+                        url: config.crowi['app:url'],
+                        appTitle: appTitle,
                       }
                       }
+                    },
+                    function(err, s) {
+                      debug('completed to send email: ', err, s);
+                      next();
+                    }
                     );
                     );
                   },
                   },
                   function(err) {
                   function(err) {
@@ -255,13 +255,14 @@ module.exports = function(crowi, app) {
                       }
                       }
                       // DONE
                       // DONE
                     });
                     });
-                  }).catch(function (err) { // ignore
+                  }).catch(function(err) { // ignore
                     debug('Upload error', err);
                     debug('Upload error', err);
                   });
                   });
                 }).catch(function() { // ignore
                 }).catch(function() { // ignore
                 });
                 });
               }
               }
-            } else {
+            }
+            else {
               // add a flash message to inform the user that processing was successful -- 2017.09.23 Yuki Takei
               // add a flash message to inform the user that processing was successful -- 2017.09.23 Yuki Takei
               // cz. loginSuccess method doesn't work on it's own when using passport
               // cz. loginSuccess method doesn't work on it's own when using passport
               //      because `req.login()` prepared by passport is not called.
               //      because `req.login()` prepared by passport is not called.
@@ -272,7 +273,8 @@ module.exports = function(crowi, app) {
           }
           }
         });
         });
       });
       });
-    } else { // method GET of form is not valid
+    }
+    else { // method GET of form is not valid
       debug('session is', req.session);
       debug('session is', req.session);
       var isRegistering = true;
       var isRegistering = true;
       // google callback を受ける可能性もある
       // google callback を受ける可能性もある
@@ -306,7 +308,8 @@ module.exports = function(crowi, app) {
           }
           }
           return res.render('login', { isRegistering, googleId, googleEmail, googleName, googleImage, });
           return res.render('login', { isRegistering, googleId, googleEmail, googleName, googleImage, });
         });
         });
-      } else {
+      }
+      else {
         return res.render('login', { isRegistering, googleId, googleEmail, googleName, googleImage, });
         return res.render('login', { isRegistering, googleId, googleEmail, googleName, googleImage, });
       }
       }
     }
     }
@@ -342,17 +345,20 @@ module.exports = function(crowi, app) {
             if (err) {
             if (err) {
               req.flash('warningMessage', 'アクティベートに失敗しました。');
               req.flash('warningMessage', 'アクティベートに失敗しました。');
               return res.render('invited');
               return res.render('invited');
-            } else {
+            }
+            else {
               return res.redirect('/');
               return res.redirect('/');
             }
             }
           });
           });
-        } else {
+        }
+        else {
           req.flash('warningMessage', '利用できないユーザーIDです。');
           req.flash('warningMessage', '利用できないユーザーIDです。');
           debug('username', username);
           debug('username', username);
           return res.render('invited');
           return res.render('invited');
         }
         }
       });
       });
-    } else {
+    }
+    else {
       return res.render('invited', {
       return res.render('invited', {
       });
       });
     }
     }

+ 51 - 44
lib/routes/page.js

@@ -54,7 +54,8 @@ module.exports = function(crowi, app) {
 
 
     if (length < limit) {
     if (length < limit) {
       next = null;
       next = null;
-    } else {
+    }
+    else {
       next = offset + limit;
       next = offset + limit;
     }
     }
 
 
@@ -77,7 +78,7 @@ module.exports = function(crowi, app) {
     else {
     else {
       return actions.pageListShowForCrowiPlus(req, res);
       return actions.pageListShowForCrowiPlus(req, res);
     }
     }
-  }
+  };
   /**
   /**
    * switch action by behaviorType
    * switch action by behaviorType
    */
    */
@@ -90,7 +91,7 @@ module.exports = function(crowi, app) {
     else {
     else {
       return actions.pageShowForCrowiPlus(req, res);
       return actions.pageShowForCrowiPlus(req, res);
     }
     }
-  }
+  };
   /**
   /**
    * switch action by behaviorType
    * switch action by behaviorType
    */
    */
@@ -105,7 +106,7 @@ module.exports = function(crowi, app) {
       // redirect to '/trash'
       // redirect to '/trash'
       return res.redirect('/trash');
       return res.redirect('/trash');
     }
     }
-  }
+  };
   /**
   /**
    * switch action by behaviorType
    * switch action by behaviorType
    */
    */
@@ -121,7 +122,7 @@ module.exports = function(crowi, app) {
       return actions.deletedPageListShow(req, res);
       return actions.deletedPageListShow(req, res);
     }
     }
 
 
-  }
+  };
   /**
   /**
    * switch action by behaviorType
    * switch action by behaviorType
    */
    */
@@ -136,7 +137,7 @@ module.exports = function(crowi, app) {
       const path = '/trash' + getPathFromRequest(req);
       const path = '/trash' + getPathFromRequest(req);
       return res.redirect(path);
       return res.redirect(path);
     }
     }
-  }
+  };
 
 
 
 
   actions.pageListShow = function(req, res) {
   actions.pageListShow = function(req, res) {
@@ -151,11 +152,11 @@ module.exports = function(crowi, app) {
     // index page
     // index page
     var pagerOptions = {
     var pagerOptions = {
       offset: offset,
       offset: offset,
-      limit : limit
+      limit: limit
     };
     };
     var queryOptions = {
     var queryOptions = {
       offset: offset,
       offset: offset,
-      limit : limit + 1,
+      limit: limit + 1,
       isPopulateRevisionBody: Config.isEnabledTimeline(config),
       isPopulateRevisionBody: Config.isEnabledTimeline(config),
     };
     };
 
 
@@ -175,7 +176,8 @@ module.exports = function(crowi, app) {
       if (portalPage) {
       if (portalPage) {
         renderVars.revision = portalPage.revision;
         renderVars.revision = portalPage.revision;
         return Revision.findRevisionList(portalPage.path, {});
         return Revision.findRevisionList(portalPage.path, {});
-      } else {
+      }
+      else {
         return Promise.resolve([]);
         return Promise.resolve([]);
       }
       }
     }).then(function(tree) {
     }).then(function(tree) {
@@ -207,7 +209,7 @@ module.exports = function(crowi, app) {
     path = path.replace((/\/$/), '');
     path = path.replace((/\/$/), '');
     // redirect
     // redirect
     return res.redirect(path);
     return res.redirect(path);
-  }
+  };
 
 
   actions.pageShowForCrowiPlus = function(req, res) {
   actions.pageShowForCrowiPlus = function(req, res) {
     var path = getPathFromRequest(req);
     var path = getPathFromRequest(req);
@@ -219,11 +221,11 @@ module.exports = function(crowi, app) {
     // index page
     // index page
     var pagerOptions = {
     var pagerOptions = {
       offset: offset,
       offset: offset,
-      limit : limit
+      limit: limit
     };
     };
     var queryOptions = {
     var queryOptions = {
       offset: offset,
       offset: offset,
-      limit : limit + 1,
+      limit: limit + 1,
       isPopulateRevisionBody: Config.isEnabledTimeline(config),
       isPopulateRevisionBody: Config.isEnabledTimeline(config),
       includeDeletedPage: path.startsWith('/trash/'),
       includeDeletedPage: path.startsWith('/trash/'),
     };
     };
@@ -296,7 +298,8 @@ module.exports = function(crowi, app) {
             return Promise.resolve();
             return Promise.resolve();
           }
           }
         });
         });
-      } else {
+      }
+      else {
         return Promise.resolve();
         return Promise.resolve();
       }
       }
     })
     })
@@ -339,14 +342,14 @@ module.exports = function(crowi, app) {
     })
     })
     .then(function() {
     .then(function() {
       return UserGroupRelation.findAllRelationForUser(req.user);
       return UserGroupRelation.findAllRelationForUser(req.user);
-    }).then(function (groupRelations) {
+    }).then(function(groupRelations) {
       debug('findPage : relatedGroups ', groupRelations);
       debug('findPage : relatedGroups ', groupRelations);
       renderVars.userRelatedGroups = groupRelations.map(relation => relation.relatedGroup);
       renderVars.userRelatedGroups = groupRelations.map(relation => relation.relatedGroup);
       debug('findPage : groups ', renderVars.userRelatedGroups);
       debug('findPage : groups ', renderVars.userRelatedGroups);
 
 
       return Promise.resolve();
       return Promise.resolve();
     });
     });
-  }
+  };
 
 
   actions.deletedPageListShow = function(req, res) {
   actions.deletedPageListShow = function(req, res) {
     var path = '/trash' + getPathFromRequest(req);
     var path = '/trash' + getPathFromRequest(req);
@@ -356,11 +359,11 @@ module.exports = function(crowi, app) {
     // index page
     // index page
     var pagerOptions = {
     var pagerOptions = {
       offset: offset,
       offset: offset,
-      limit : limit
+      limit: limit
     };
     };
     var queryOptions = {
     var queryOptions = {
       offset: offset,
       offset: offset,
-      limit : limit + 1,
+      limit: limit + 1,
       includeDeletedPage: true,
       includeDeletedPage: true,
     };
     };
 
 
@@ -466,7 +469,8 @@ module.exports = function(crowi, app) {
           debug('Error on finding user related entities', err);
           debug('Error on finding user related entities', err);
           // pass
           // pass
         });
         });
-      } else {
+      }
+      else {
         return Promise.resolve();
         return Promise.resolve();
       }
       }
     }).then(function() {
     }).then(function() {
@@ -531,11 +535,12 @@ module.exports = function(crowi, app) {
       .then(function(page) {
       .then(function(page) {
         if (page) {
         if (page) {
           return res.redirect(pagePathUtil.encodePagePath(path) + '/');
           return res.redirect(pagePathUtil.encodePagePath(path) + '/');
-        } else {
+        }
+        else {
 
 
-          var fixed = Page.fixToCreatableName(path)
+          var fixed = Page.fixToCreatableName(path);
           if (fixed !== path) {
           if (fixed !== path) {
-            debug('fixed page name', fixed)
+            debug('fixed page name', fixed);
             res.redirect(pagePathUtil.encodePagePath(fixed));
             res.redirect(pagePathUtil.encodePagePath(fixed));
             return ;
             return ;
           }
           }
@@ -562,7 +567,7 @@ module.exports = function(crowi, app) {
     var currentRevision = pageForm.currentRevision;
     var currentRevision = pageForm.currentRevision;
     var grant = pageForm.grant;
     var grant = pageForm.grant;
     var path = pageForm.path;
     var path = pageForm.path;
-    var grantUserGroupId = pageForm.grantUserGroupId
+    var grantUserGroupId = pageForm.grantUserGroupId;
 
 
     // TODO: make it pluggable
     // TODO: make it pluggable
     var notify = pageForm.notify || {};
     var notify = pageForm.notify || {};
@@ -602,7 +607,8 @@ module.exports = function(crowi, app) {
       if (data) {
       if (data) {
         previousRevision = data.revision;
         previousRevision = data.revision;
         return Page.updatePage(data, body, req.user, { grant: grant, grantUserGroupId: grantUserGroupId});
         return Page.updatePage(data, body, req.user, { grant: grant, grantUserGroupId: grantUserGroupId});
-      } else {
+      }
+      else {
         // new page
         // new page
         updateOrCreate = 'create';
         updateOrCreate = 'create';
         return Page.create(path, body, req.user, { grant: grant, grantUserGroupId: grantUserGroupId});
         return Page.create(path, body, req.user, { grant: grant, grantUserGroupId: grantUserGroupId});
@@ -616,7 +622,7 @@ module.exports = function(crowi, app) {
       // TODO: move to events
       // TODO: move to events
       if (notify.slack) {
       if (notify.slack) {
         if (notify.slack.on && notify.slack.channel) {
         if (notify.slack.on && notify.slack.channel) {
-          data.updateSlackChannel(notify.slack.channel).then(function(){}).catch(function(){});
+          data.updateSlackChannel(notify.slack.channel).then(function() {}).catch(function() {});
 
 
           if (crowi.slack) {
           if (crowi.slack) {
             notify.slack.channel.split(',').map(function(chan) {
             notify.slack.channel.split(',').map(function(chan) {
@@ -647,7 +653,7 @@ module.exports = function(crowi, app) {
   /**
   /**
    * redirector
    * redirector
    */
    */
-  api.redirector = function(req, res){
+  api.redirector = function(req, res) {
     var id = req.params.id;
     var id = req.params.id;
 
 
     Page.findPageById(id)
     Page.findPageById(id)
@@ -680,8 +686,8 @@ module.exports = function(crowi, app) {
     var limit = 50;
     var limit = 50;
     var offset = parseInt(req.query.offset) || 0;
     var offset = parseInt(req.query.offset) || 0;
 
 
-    var pagerOptions = { offset: offset, limit : limit };
-    var queryOptions = { offset: offset, limit : limit + 1};
+    var pagerOptions = { offset: offset, limit: limit };
+    var queryOptions = { offset: offset, limit: limit + 1};
 
 
     // Accepts only one of these
     // Accepts only one of these
     if (username === null && path === null) {
     if (username === null && path === null) {
@@ -700,7 +706,8 @@ module.exports = function(crowi, app) {
         }
         }
         return Page.findListByCreator(user, queryOptions, req.user);
         return Page.findListByCreator(user, queryOptions, req.user);
       });
       });
-    } else {
+    }
+    else {
       pageFetcher = Page.findListByStartWith(path, req.user, queryOptions);
       pageFetcher = Page.findListByStartWith(path, req.user, queryOptions);
     }
     }
 
 
@@ -728,7 +735,7 @@ module.exports = function(crowi, app) {
    * @apiParam {String} path
    * @apiParam {String} path
    * @apiParam {String} grant
    * @apiParam {String} grant
    */
    */
-  api.create = function(req, res){
+  api.create = function(req, res) {
     var body = req.body.body || null;
     var body = req.body.body || null;
     var pagePath = req.body.path || null;
     var pagePath = req.body.path || null;
     var grant = req.body.grant || null;
     var grant = req.body.grant || null;
@@ -757,7 +764,7 @@ module.exports = function(crowi, app) {
       return res.json(ApiResponse.success(result));
       return res.json(ApiResponse.success(result));
     }).catch(function(err) {
     }).catch(function(err) {
       return res.json(ApiResponse.error(err));
       return res.json(ApiResponse.error(err));
-    });;
+    });
 
 
   };
   };
 
 
@@ -775,7 +782,7 @@ module.exports = function(crowi, app) {
    * - If revision_id is specified => update the page,
    * - If revision_id is specified => update the page,
    * - If revision_id is not specified => force update by the new contents.
    * - If revision_id is not specified => force update by the new contents.
    */
    */
-  api.update = function(req, res){
+  api.update = function(req, res) {
     var pageBody = req.body.body || null;
     var pageBody = req.body.body || null;
     var pageId = req.body.page_id || null;
     var pageId = req.body.page_id || null;
     var revisionId = req.body.revision_id || null;
     var revisionId = req.body.revision_id || null;
@@ -790,7 +797,7 @@ module.exports = function(crowi, app) {
     .then(function(pageData) {
     .then(function(pageData) {
       if (pageData && revisionId !== null && !pageData.isUpdatable(revisionId)) {
       if (pageData && revisionId !== null && !pageData.isUpdatable(revisionId)) {
         throw new Error('Revision error.');
         throw new Error('Revision error.');
-      };
+      }
 
 
       var grantOption = {grant: pageData.grant};
       var grantOption = {grant: pageData.grant};
       if (grant !== null) {
       if (grant !== null) {
@@ -821,7 +828,7 @@ module.exports = function(crowi, app) {
    * @apiParam {String} path
    * @apiParam {String} path
    * @apiParam {String} revision_id
    * @apiParam {String} revision_id
    */
    */
-  api.get = function(req, res){
+  api.get = function(req, res) {
     const pagePath = req.query.path || null;
     const pagePath = req.query.path || null;
     const pageId = req.query.page_id || null; // TODO: handling
     const pageId = req.query.page_id || null; // TODO: handling
     const revisionId = req.query.revision_id || null;
     const revisionId = req.query.revision_id || null;
@@ -833,7 +840,8 @@ module.exports = function(crowi, app) {
     let pageFinder;
     let pageFinder;
     if (pageId) { // prioritized
     if (pageId) { // prioritized
       pageFinder = Page.findPageByIdAndGrantedUser(pageId, req.user);
       pageFinder = Page.findPageByIdAndGrantedUser(pageId, req.user);
-    } else if (pagePath) {
+    }
+    else if (pagePath) {
       pageFinder = Page.findPage(pagePath, req.user, revisionId);
       pageFinder = Page.findPage(pagePath, req.user, revisionId);
     }
     }
 
 
@@ -854,7 +862,7 @@ module.exports = function(crowi, app) {
    *
    *
    * @apiParam {String} page_id Page Id.
    * @apiParam {String} page_id Page Id.
    */
    */
-  api.seen = function(req, res){
+  api.seen = function(req, res) {
     var pageId = req.body.page_id;
     var pageId = req.body.page_id;
     if (!pageId) {
     if (!pageId) {
       return res.json(ApiResponse.error('page_id required'));
       return res.json(ApiResponse.error('page_id required'));
@@ -881,7 +889,7 @@ module.exports = function(crowi, app) {
    *
    *
    * @apiParam {String} page_id Page Id.
    * @apiParam {String} page_id Page Id.
    */
    */
-  api.like = function(req, res){
+  api.like = function(req, res) {
     var id = req.body.page_id;
     var id = req.body.page_id;
 
 
     Page.findPageByIdAndGrantedUser(id, req.user)
     Page.findPageByIdAndGrantedUser(id, req.user)
@@ -903,7 +911,7 @@ module.exports = function(crowi, app) {
    *
    *
    * @apiParam {String} page_id Page Id.
    * @apiParam {String} page_id Page Id.
    */
    */
-  api.unlike = function(req, res){
+  api.unlike = function(req, res) {
     var id = req.body.page_id;
     var id = req.body.page_id;
 
 
     Page.findPageByIdAndGrantedUser(id, req.user)
     Page.findPageByIdAndGrantedUser(id, req.user)
@@ -955,7 +963,7 @@ module.exports = function(crowi, app) {
    * @apiParam {String} page_id Page Id.
    * @apiParam {String} page_id Page Id.
    * @apiParam {String} revision_id
    * @apiParam {String} revision_id
    */
    */
-  api.remove = function(req, res){
+  api.remove = function(req, res) {
     var pageId = req.body.page_id;
     var pageId = req.body.page_id;
     var previousRevision = req.body.revision_id || null;
     var previousRevision = req.body.revision_id || null;
 
 
@@ -1008,7 +1016,7 @@ module.exports = function(crowi, app) {
    *
    *
    * @apiParam {String} page_id Page Id.
    * @apiParam {String} page_id Page Id.
    */
    */
-  api.revertRemove = function(req, res){
+  api.revertRemove = function(req, res) {
     var pageId = req.body.page_id;
     var pageId = req.body.page_id;
 
 
     // get recursively flag
     // get recursively flag
@@ -1046,7 +1054,7 @@ module.exports = function(crowi, app) {
    * @apiParam {String} new_path
    * @apiParam {String} new_path
    * @apiParam {Bool} create_redirect
    * @apiParam {Bool} create_redirect
    */
    */
-  api.rename = function(req, res){
+  api.rename = function(req, res) {
     var pageId = req.body.page_id;
     var pageId = req.body.page_id;
     var previousRevision = req.body.revision_id || null;
     var previousRevision = req.body.revision_id || null;
     var newPagePath = Page.normalizePath(req.body.new_path);
     var newPagePath = Page.normalizePath(req.body.new_path);
@@ -1100,13 +1108,12 @@ module.exports = function(crowi, app) {
    * @apiParam {String} page_id Page Id.
    * @apiParam {String} page_id Page Id.
    * @apiParam {String} new_path
    * @apiParam {String} new_path
    */
    */
-  api.duplicate = function (req, res) {
+  api.duplicate = function(req, res) {
     var pageId = req.body.page_id;
     var pageId = req.body.page_id;
     var newPagePath = Page.normalizePath(req.body.new_path);
     var newPagePath = Page.normalizePath(req.body.new_path);
-    var page = {};
 
 
     Page.findPageById(pageId)
     Page.findPageById(pageId)
-      .then(function (pageData) {
+      .then(function(pageData) {
         req.body.path = newPagePath;
         req.body.path = newPagePath;
         req.body.body = pageData.revision.body;
         req.body.body = pageData.revision.body;
         req.body.grant = pageData.grant;
         req.body.grant = pageData.grant;
@@ -1123,7 +1130,7 @@ module.exports = function(crowi, app) {
    * @apiParam {String} page_id Page Id.
    * @apiParam {String} page_id Page Id.
    * @apiParam {String} revision_id
    * @apiParam {String} revision_id
    */
    */
-  api.unlink = function(req, res){
+  api.unlink = function(req, res) {
     var pageId = req.body.page_id;
     var pageId = req.body.page_id;
 
 
     Page.findPageByIdAndGrantedUser(pageId, req.user)
     Page.findPageByIdAndGrantedUser(pageId, req.user)

+ 47 - 60
lib/util/search.js

@@ -33,9 +33,9 @@ SearchClient.prototype.checkESVersion = function() {
 
 
 SearchClient.prototype.registerUpdateEvent = function() {
 SearchClient.prototype.registerUpdateEvent = function() {
   var pageEvent = this.crowi.event('page');
   var pageEvent = this.crowi.event('page');
-  pageEvent.on('create', this.syncPageCreated.bind(this))
-  pageEvent.on('update', this.syncPageUpdated.bind(this))
-  pageEvent.on('delete', this.syncPageDeleted.bind(this))
+  pageEvent.on('create', this.syncPageCreated.bind(this));
+  pageEvent.on('update', this.syncPageUpdated.bind(this));
+  pageEvent.on('delete', this.syncPageDeleted.bind(this));
 };
 };
 
 
 SearchClient.prototype.shouldIndexed = function(page) {
 SearchClient.prototype.shouldIndexed = function(page) {
@@ -159,8 +159,7 @@ SearchClient.prototype.prepareBodyForDelete = function(body, page) {
 };
 };
 
 
 
 
-SearchClient.prototype.addPages = function(pages)
-{
+SearchClient.prototype.addPages = function(pages) {
   var self = this;
   var self = this;
   var body = [];
   var body = [];
 
 
@@ -174,8 +173,7 @@ SearchClient.prototype.addPages = function(pages)
   });
   });
 };
 };
 
 
-SearchClient.prototype.updatePages = function(pages)
-{
+SearchClient.prototype.updatePages = function(pages) {
   var self = this;
   var self = this;
   var body = [];
   var body = [];
 
 
@@ -189,8 +187,7 @@ SearchClient.prototype.updatePages = function(pages)
   });
   });
 };
 };
 
 
-SearchClient.prototype.deletePages = function(pages)
-{
+SearchClient.prototype.deletePages = function(pages) {
   var self = this;
   var self = this;
   var body = [];
   var body = [];
 
 
@@ -204,8 +201,7 @@ SearchClient.prototype.deletePages = function(pages)
   });
   });
 };
 };
 
 
-SearchClient.prototype.addAllPages = function()
-{
+SearchClient.prototype.addAllPages = function() {
   var self = this;
   var self = this;
   var Page = this.crowi.model('Page');
   var Page = this.crowi.model('Page');
   var cursor = Page.getStreamOfFindAll();
   var cursor = Page.getStreamOfFindAll();
@@ -214,7 +210,7 @@ SearchClient.prototype.addAllPages = function()
   var skipped = 0;
   var skipped = 0;
 
 
   return new Promise(function(resolve, reject) {
   return new Promise(function(resolve, reject) {
-    cursor.on('data', function (doc) {
+    cursor.on('data', function(doc) {
       if (!doc.creator || !doc.revision || !self.shouldIndexed(doc)) {
       if (!doc.creator || !doc.revision || !self.shouldIndexed(doc)) {
         //debug('Skipped', doc.path);
         //debug('Skipped', doc.path);
         skipped++;
         skipped++;
@@ -230,17 +226,17 @@ SearchClient.prototype.addAllPages = function()
           body: body,
           body: body,
           requestTimeout: Infinity,
           requestTimeout: Infinity,
         }).then(res => {
         }).then(res => {
-          debug('addAllPages add anyway (items, errors, took): ', (res.items || []).length, res.errors, res.took)
+          debug('addAllPages add anyway (items, errors, took): ', (res.items || []).length, res.errors, res.took);
         }).catch(err => {
         }).catch(err => {
-          debug('addAllPages error on add anyway: ', err)
+          debug('addAllPages error on add anyway: ', err);
         });
         });
 
 
         body = [];
         body = [];
       }
       }
-    }).on('error', function (err) {
+    }).on('error', function(err) {
       // TODO: handle err
       // TODO: handle err
       debug('Error cursor:', err);
       debug('Error cursor:', err);
-    }).on('close', function () {
+    }).on('close', function() {
       // all done
       // all done
 
 
       // return if body is empty
       // return if body is empty
@@ -272,8 +268,7 @@ SearchClient.prototype.addAllPages = function()
  *   data: [ pages ...],
  *   data: [ pages ...],
  * }
  * }
  */
  */
-SearchClient.prototype.search = function(query)
-{
+SearchClient.prototype.search = function(query) {
   var self = this;
   var self = this;
 
 
   return new Promise(function(resolve, reject) {
   return new Promise(function(resolve, reject) {
@@ -297,8 +292,7 @@ SearchClient.prototype.search = function(query)
   });
   });
 };
 };
 
 
-SearchClient.prototype.createSearchQuerySortedByUpdatedAt = function(option)
-{
+SearchClient.prototype.createSearchQuerySortedByUpdatedAt = function(option) {
   // getting path by default is almost for debug
   // getting path by default is almost for debug
   var fields = ['path'];
   var fields = ['path'];
   if (option) {
   if (option) {
@@ -320,8 +314,7 @@ SearchClient.prototype.createSearchQuerySortedByUpdatedAt = function(option)
   return query;
   return query;
 };
 };
 
 
-SearchClient.prototype.createSearchQuerySortedByScore = function(option)
-{
+SearchClient.prototype.createSearchQuerySortedByScore = function(option) {
   var fields = ['path'];
   var fields = ['path'];
   if (option) {
   if (option) {
     fields = option.fields || fields;
     fields = option.fields || fields;
@@ -342,14 +335,12 @@ SearchClient.prototype.createSearchQuerySortedByScore = function(option)
   return query;
   return query;
 };
 };
 
 
-SearchClient.prototype.appendResultSize = function(query, from, size)
-{
+SearchClient.prototype.appendResultSize = function(query, from, size) {
   query.from = from || this.DEFAULT_OFFSET;
   query.from = from || this.DEFAULT_OFFSET;
   query.size = size || this.DEFAULT_LIMIT;
   query.size = size || this.DEFAULT_LIMIT;
 };
 };
 
 
-SearchClient.prototype.appendCriteriaForKeywordContains = function(query, keyword)
-{
+SearchClient.prototype.appendCriteriaForKeywordContains = function(query, keyword) {
   // query is created by createSearchQuerySortedByScore() or createSearchQuerySortedByUpdatedAt()
   // query is created by createSearchQuerySortedByScore() or createSearchQuerySortedByUpdatedAt()
   if (!query.body.query.bool) {
   if (!query.body.query.bool) {
     query.body.query.bool = {};
     query.body.query.bool = {};
@@ -379,9 +370,9 @@ SearchClient.prototype.appendCriteriaForKeywordContains = function(query, keywor
         query: keywords.join(' '),
         query: keywords.join(' '),
         // TODO: By user's i18n setting, change boost or search target fields
         // TODO: By user's i18n setting, change boost or search target fields
         fields: [
         fields: [
-          "path_ja^2",
-          "path_en^2",
-          "body_ja",
+          'path_ja^2',
+          'path_en^2',
+          'body_ja',
           // "path_en",
           // "path_en",
           // "body_en",
           // "body_en",
         ],
         ],
@@ -410,8 +401,8 @@ SearchClient.prototype.appendCriteriaForKeywordContains = function(query, keywor
           query: phrase, // each phrase is quoteted words
           query: phrase, // each phrase is quoteted words
           type: 'phrase',
           type: 'phrase',
           fields: [ // Not use "*.ja" fields here, because we want to analyze (parse) search words
           fields: [ // Not use "*.ja" fields here, because we want to analyze (parse) search words
-            "path_raw^2",
-            "body_raw",
+            'path_raw^2',
+            'body_raw',
           ],
           ],
         }
         }
       });
       });
@@ -428,8 +419,8 @@ SearchClient.prototype.appendCriteriaForKeywordContains = function(query, keywor
           query: phrase, // each phrase is quoteted words
           query: phrase, // each phrase is quoteted words
           type: 'phrase',
           type: 'phrase',
           fields: [ // Not use "*.ja" fields here, because we want to analyze (parse) search words
           fields: [ // Not use "*.ja" fields here, because we want to analyze (parse) search words
-            "path_raw^2",
-            "body_raw",
+            'path_raw^2',
+            'body_raw',
           ],
           ],
         }
         }
       });
       });
@@ -439,8 +430,7 @@ SearchClient.prototype.appendCriteriaForKeywordContains = function(query, keywor
   }
   }
 };
 };
 
 
-SearchClient.prototype.appendCriteriaForPathFilter = function(query, path)
-{
+SearchClient.prototype.appendCriteriaForPathFilter = function(query, path) {
   // query is created by createSearchQuerySortedByScore() or createSearchQuerySortedByUpdatedAt()
   // query is created by createSearchQuerySortedByScore() or createSearchQuerySortedByUpdatedAt()
   if (!query.body.query.bool) {
   if (!query.body.query.bool) {
     query.body.query.bool = {};
     query.body.query.bool = {};
@@ -455,27 +445,26 @@ SearchClient.prototype.appendCriteriaForPathFilter = function(query, path)
   }
   }
   query.body.query.bool.filter.push({
   query.body.query.bool.filter.push({
     wildcard: {
     wildcard: {
-      "path": path + "/*"
+      'path': path + '/*'
     }
     }
   });
   });
 };
 };
 
 
-SearchClient.prototype.searchKeyword = function(keyword, option)
-{
+SearchClient.prototype.searchKeyword = function(keyword, option) {
+  /* eslint-disable no-unused-vars */
   var from = option.offset || null;
   var from = option.offset || null;
+  /* eslint-enable */
   var query = this.createSearchQuerySortedByScore();
   var query = this.createSearchQuerySortedByScore();
   this.appendCriteriaForKeywordContains(query, keyword);
   this.appendCriteriaForKeywordContains(query, keyword);
 
 
   return this.search(query);
   return this.search(query);
 };
 };
 
 
-SearchClient.prototype.searchByPath = function(keyword, prefix)
-{
+SearchClient.prototype.searchByPath = function(keyword, prefix) {
   // TODO path 名だけから検索
   // TODO path 名だけから検索
 };
 };
 
 
-SearchClient.prototype.searchKeywordUnderPath = function(keyword, path, option)
-{
+SearchClient.prototype.searchKeywordUnderPath = function(keyword, path, option) {
   var from = option.offset || null;
   var from = option.offset || null;
   var query = this.createSearchQuerySortedByScore();
   var query = this.createSearchQuerySortedByScore();
   this.appendCriteriaForKeywordContains(query, keyword);
   this.appendCriteriaForKeywordContains(query, keyword);
@@ -488,8 +477,7 @@ SearchClient.prototype.searchKeywordUnderPath = function(keyword, path, option)
   return this.search(query);
   return this.search(query);
 };
 };
 
 
-SearchClient.prototype.getParsedKeywords = function(keyword)
-{
+SearchClient.prototype.getParsedKeywords = function(keyword) {
   var matchWords = [];
   var matchWords = [];
   var notMatchWords = [];
   var notMatchWords = [];
   var phraseWords = [];
   var phraseWords = [];
@@ -507,9 +495,10 @@ SearchClient.prototype.getParsedKeywords = function(keyword)
 
 
     phrases.forEach(function(phrase) {
     phrases.forEach(function(phrase) {
       phrase.trim();
       phrase.trim();
-      if (phrase.match(/^\-/)) {
-        notPhraseWords.push(phrase.replace(/^\-/, ''));
-      } else {
+      if (phrase.match(/^-/)) {
+        notPhraseWords.push(phrase.replace(/^-/, ''));
+      }
+      else {
         phraseWords.push(phrase);
         phraseWords.push(phrase);
       }
       }
     });
     });
@@ -521,9 +510,10 @@ SearchClient.prototype.getParsedKeywords = function(keyword)
       return;
       return;
     }
     }
 
 
-    if (word.match(/^\-(.+)$/)) {
+    if (word.match(/^-(.+)$/)) {
       notMatchWords.push((RegExp.$1));
       notMatchWords.push((RegExp.$1));
-    } else {
+    }
+    else {
       matchWords.push(word);
       matchWords.push(word);
     }
     }
   });
   });
@@ -534,10 +524,9 @@ SearchClient.prototype.getParsedKeywords = function(keyword)
     phrase: phraseWords,
     phrase: phraseWords,
     not_phrase: notPhraseWords,
     not_phrase: notPhraseWords,
   };
   };
-}
+};
 
 
-SearchClient.prototype.syncPageCreated = function(page, user)
-{
+SearchClient.prototype.syncPageCreated = function(page, user) {
   debug('SearchClient.syncPageCreated', page.path);
   debug('SearchClient.syncPageCreated', page.path);
 
 
   if (!this.shouldIndexed(page)) {
   if (!this.shouldIndexed(page)) {
@@ -548,13 +537,12 @@ SearchClient.prototype.syncPageCreated = function(page, user)
   .then(function(res) {
   .then(function(res) {
     debug('ES Response', res);
     debug('ES Response', res);
   })
   })
-  .catch(function(err){
+  .catch(function(err) {
     debug('ES Error', err);
     debug('ES Error', err);
   });
   });
 };
 };
 
 
-SearchClient.prototype.syncPageUpdated = function(page, user)
-{
+SearchClient.prototype.syncPageUpdated = function(page, user) {
   debug('SearchClient.syncPageUpdated', page.path);
   debug('SearchClient.syncPageUpdated', page.path);
   // TODO delete
   // TODO delete
   if (!this.shouldIndexed(page)) {
   if (!this.shouldIndexed(page)) {
@@ -562,7 +550,7 @@ SearchClient.prototype.syncPageUpdated = function(page, user)
     .then(function(res) {
     .then(function(res) {
       debug('deletePages: ES Response', res);
       debug('deletePages: ES Response', res);
     })
     })
-    .catch(function(err){
+    .catch(function(err) {
       debug('deletePages:ES Error', err);
       debug('deletePages:ES Error', err);
     });
     });
 
 
@@ -573,20 +561,19 @@ SearchClient.prototype.syncPageUpdated = function(page, user)
   .then(function(res) {
   .then(function(res) {
     debug('ES Response', res);
     debug('ES Response', res);
   })
   })
-  .catch(function(err){
+  .catch(function(err) {
     debug('ES Error', err);
     debug('ES Error', err);
   });
   });
 };
 };
 
 
-SearchClient.prototype.syncPageDeleted = function(page, user)
-{
+SearchClient.prototype.syncPageDeleted = function(page, user) {
   debug('SearchClient.syncPageDeleted', page.path);
   debug('SearchClient.syncPageDeleted', page.path);
 
 
   this.deletePages([page])
   this.deletePages([page])
   .then(function(res) {
   .then(function(res) {
     debug('deletePages: ES Response', res);
     debug('deletePages: ES Response', res);
   })
   })
-  .catch(function(err){
+  .catch(function(err) {
     debug('deletePages:ES Error', err);
     debug('deletePages:ES Error', err);
   });
   });
 
 

+ 21 - 17
lib/util/slack.js

@@ -5,8 +5,6 @@
 module.exports = function(crowi) {
 module.exports = function(crowi) {
   'use strict';
   'use strict';
 
 
-  const SLACK_URL = 'https://slack.com';
-
   const debug = require('debug')('growi:util:slack'),
   const debug = require('debug')('growi:util:slack'),
     config = crowi.getConfig(),
     config = crowi.getConfig(),
     Config = crowi.model('Config'),
     Config = crowi.model('Config'),
@@ -17,7 +15,7 @@ module.exports = function(crowi) {
     const client = new Slack();
     const client = new Slack();
     client.setWebhook(config.notification['slack:incomingWebhookUrl']);
     client.setWebhook(config.notification['slack:incomingWebhookUrl']);
     client.webhook(messageObj, callback);
     client.webhook(messageObj, callback);
-  }
+  };
 
 
   const postWithWebApi = function(messageObj, callback) {
   const postWithWebApi = function(messageObj, callback) {
     const client = new Slack(config.notification['slack:token']);
     const client = new Slack(config.notification['slack:token']);
@@ -26,7 +24,7 @@ module.exports = function(crowi) {
       messageObj.attachments = JSON.stringify(messageObj.attachments);
       messageObj.attachments = JSON.stringify(messageObj.attachments);
     }
     }
     client.api('chat.postMessage', messageObj, callback);
     client.api('chat.postMessage', messageObj, callback);
-  }
+  };
 
 
   const convertMarkdownToMrkdwn = function(body) {
   const convertMarkdownToMrkdwn = function(body) {
     var url = '';
     var url = '';
@@ -39,7 +37,7 @@ module.exports = function(crowi) {
       .replace(/#{1,}\s?(.+)/g, '\n*$1*')
       .replace(/#{1,}\s?(.+)/g, '\n*$1*')
       .replace(/(\[(.+)\]\((https?:\/\/.+)\))/g, '<$3|$2>')
       .replace(/(\[(.+)\]\((https?:\/\/.+)\))/g, '<$3|$2>')
       .replace(/(\[(.+)\]\((\/.+)\))/g, '<' + url + '$3|$2>')
       .replace(/(\[(.+)\]\((\/.+)\))/g, '<' + url + '$3|$2>')
-      ;
+    ;
 
 
     return body;
     return body;
   };
   };
@@ -55,25 +53,29 @@ module.exports = function(crowi) {
 
 
   const prepareAttachmentTextForUpdate = function(page, user, previousRevision) {
   const prepareAttachmentTextForUpdate = function(page, user, previousRevision) {
     var diff = require('diff');
     var diff = require('diff');
-    var diffText = ''
+    var diffText = '';
 
 
     diff.diffLines(previousRevision.body, page.revision.body).forEach(function(line) {
     diff.diffLines(previousRevision.body, page.revision.body).forEach(function(line) {
-      debug('diff line', line)
+      debug('diff line', line);
+      /* eslint-disable no-unused-vars */
       var value = line.value.replace(/\r\n|\r/g, '\n');
       var value = line.value.replace(/\r\n|\r/g, '\n');
+      /* eslint-enable */
       if (line.added) {
       if (line.added) {
         diffText += `:pencil2: ...\n${line.value}`;
         diffText += `:pencil2: ...\n${line.value}`;
-      } else if (line.removed) {
+      }
+      else if (line.removed) {
         // diffText += '-' + line.value.replace(/(.+)?\n/g, '- $1\n');
         // diffText += '-' + line.value.replace(/(.+)?\n/g, '- $1\n');
         // 1以下は無視
         // 1以下は無視
         if (line.count > 1) {
         if (line.count > 1) {
           diffText += `:wastebasket: ... ${line.count} lines\n`;
           diffText += `:wastebasket: ... ${line.count} lines\n`;
         }
         }
-      } else {
+      }
+      else {
         //diffText += '...\n';
         //diffText += '...\n';
       }
       }
     });
     });
 
 
-    debug('diff is', diffText)
+    debug('diff is', diffText);
 
 
     return diffText;
     return diffText;
   };
   };
@@ -84,7 +86,8 @@ module.exports = function(crowi) {
 
 
     if (updateType == 'create') {
     if (updateType == 'create') {
       body = prepareAttachmentTextForCreate(page, user);
       body = prepareAttachmentTextForCreate(page, user);
-    } else {
+    }
+    else {
       body = prepareAttachmentTextForUpdate(page, user, previousRevision);
       body = prepareAttachmentTextForUpdate(page, user, previousRevision);
     }
     }
 
 
@@ -96,7 +99,7 @@ module.exports = function(crowi) {
       title: page.path,
       title: page.path,
       title_link: url + '/' + page._id,
       title_link: url + '/' + page._id,
       text: body,
       text: body,
-      mrkdwn_in: ["text"],
+      mrkdwn_in: ['text'],
     };
     };
     if (user.image) {
     if (user.image) {
       attachment.author_icon = user.image;
       attachment.author_icon = user.image;
@@ -119,7 +122,8 @@ module.exports = function(crowi) {
     const pageUrl = `<${url}${path}|${path}>`;
     const pageUrl = `<${url}${path}|${path}>`;
     if (updateType == 'create') {
     if (updateType == 'create') {
       text = `:white_check_mark: ${user.username} created a new page! ${pageUrl}`;
       text = `:white_check_mark: ${user.username} created a new page! ${pageUrl}`;
-    } else {
+    }
+    else {
       text = `:up: ${user.username} updated ${pageUrl}`;
       text = `:up: ${user.username} updated ${pageUrl}`;
     }
     }
 
 
@@ -144,22 +148,22 @@ module.exports = function(crowi) {
       // when incoming Webhooks is prioritized
       // when incoming Webhooks is prioritized
       if (Config.isIncomingWebhookPrioritized(config)) {
       if (Config.isIncomingWebhookPrioritized(config)) {
         if (Config.hasSlackIwhUrl(config)) {
         if (Config.hasSlackIwhUrl(config)) {
-          debug(`posting message with IncomingWebhook`);
+          debug('posting message with IncomingWebhook');
           postWithIwh(messageObj, callback);
           postWithIwh(messageObj, callback);
         }
         }
         else if (Config.hasSlackToken(config)) {
         else if (Config.hasSlackToken(config)) {
-          debug(`posting message with Web API`);
+          debug('posting message with Web API');
           postWithWebApi(messageObj, callback);
           postWithWebApi(messageObj, callback);
         }
         }
       }
       }
       // else
       // else
       else {
       else {
         if (Config.hasSlackToken(config)) {
         if (Config.hasSlackToken(config)) {
-          debug(`posting message with Web API`);
+          debug('posting message with Web API');
           postWithWebApi(messageObj, callback);
           postWithWebApi(messageObj, callback);
         }
         }
         else if (Config.hasSlackIwhUrl(config)) {
         else if (Config.hasSlackIwhUrl(config)) {
-          debug(`posting message with IncomingWebhook`);
+          debug('posting message with IncomingWebhook');
           postWithIwh(messageObj, callback);
           postWithIwh(messageObj, callback);
         }
         }
       }
       }

+ 43 - 41
lib/util/swigFunctions.js

@@ -6,19 +6,21 @@ module.exports = function(crowi, app, req, locals) {
     , passportService = crowi.passportService
     , passportService = crowi.passportService
   ;
   ;
 
 
+  debug('initializing swigFunctions');
+
   locals.nodeVersion = function() {
   locals.nodeVersion = function() {
     return crowi.runtimeVersions.versions.node ? crowi.runtimeVersions.versions.node.version : '-';
     return crowi.runtimeVersions.versions.node ? crowi.runtimeVersions.versions.node.version : '-';
-  }
+  };
   locals.npmVersion = function() {
   locals.npmVersion = function() {
     return crowi.runtimeVersions.versions.npm ? crowi.runtimeVersions.versions.npm.version : '-';
     return crowi.runtimeVersions.versions.npm ? crowi.runtimeVersions.versions.npm.version : '-';
-  }
+  };
   locals.yarnVersion = function() {
   locals.yarnVersion = function() {
     return crowi.runtimeVersions.versions.yarn ? crowi.runtimeVersions.versions.yarn.version : '-';
     return crowi.runtimeVersions.versions.yarn ? crowi.runtimeVersions.versions.yarn.version : '-';
-  }
+  };
 
 
   locals.growiVersion = function() {
   locals.growiVersion = function() {
     return crowi.version;
     return crowi.version;
-  }
+  };
 
 
   // token getter
   // token getter
   locals.csrf = function() {
   locals.csrf = function() {
@@ -35,7 +37,7 @@ module.exports = function(crowi, app, req, locals) {
       fontSize = 11;
       fontSize = 11;
     }
     }
     return fontSize;
     return fontSize;
-  }
+  };
 
 
   /**
   /**
    * return app title
    * return app title
@@ -43,7 +45,7 @@ module.exports = function(crowi, app, req, locals) {
   locals.appTitle = function() {
   locals.appTitle = function() {
     var config = crowi.getConfig();
     var config = crowi.getConfig();
     return Config.appTitle(config);
     return Config.appTitle(config);
-  }
+  };
 
 
   /**
   /**
    * return true if enabled
    * return true if enabled
@@ -51,7 +53,7 @@ module.exports = function(crowi, app, req, locals) {
   locals.isEnabledPassport = function() {
   locals.isEnabledPassport = function() {
     var config = crowi.getConfig();
     var config = crowi.getConfig();
     return Config.isEnabledPassport(config);
     return Config.isEnabledPassport(config);
-  }
+  };
 
 
   /**
   /**
    * return true if local strategy has been setup successfully
    * return true if local strategy has been setup successfully
@@ -59,23 +61,23 @@ module.exports = function(crowi, app, req, locals) {
    */
    */
   locals.isPassportLocalStrategySetup = function() {
   locals.isPassportLocalStrategySetup = function() {
     return passportService != null && passportService.isLocalStrategySetup;
     return passportService != null && passportService.isLocalStrategySetup;
-  }
+  };
 
 
   /**
   /**
    * return true if enabled and strategy has been setup successfully
    * return true if enabled and strategy has been setup successfully
    */
    */
   locals.isLdapSetup = function() {
   locals.isLdapSetup = function() {
-    var config = crowi.getConfig()
+    var config = crowi.getConfig();
     return Config.isEnabledPassport(config) && Config.isEnabledPassportLdap(config) && passportService.isLdapStrategySetup;
     return Config.isEnabledPassport(config) && Config.isEnabledPassportLdap(config) && passportService.isLdapStrategySetup;
-  }
+  };
 
 
   /**
   /**
    * return true if enabled but strategy has some problem
    * return true if enabled but strategy has some problem
    */
    */
   locals.isLdapSetupFailed = function() {
   locals.isLdapSetupFailed = function() {
-    var config = crowi.getConfig()
+    var config = crowi.getConfig();
     return Config.isEnabledPassport(config) && Config.isEnabledPassportLdap(config) && !passportService.isLdapStrategySetup;
     return Config.isEnabledPassport(config) && Config.isEnabledPassportLdap(config) && !passportService.isLdapStrategySetup;
-  }
+  };
 
 
   locals.googleLoginEnabled = function() {
   locals.googleLoginEnabled = function() {
     // return false if Passport is enabled
     // return false if Passport is enabled
@@ -84,7 +86,7 @@ module.exports = function(crowi, app, req, locals) {
       return false;
       return false;
     }
     }
 
 
-    var config = crowi.getConfig()
+    var config = crowi.getConfig();
     return config.crowi['google:clientId'] && config.crowi['google:clientSecret'];
     return config.crowi['google:clientId'] && config.crowi['google:clientSecret'];
   };
   };
 
 
@@ -96,70 +98,70 @@ module.exports = function(crowi, app, req, locals) {
   };
   };
 
 
   locals.isEnabledPlugins = function() {
   locals.isEnabledPlugins = function() {
-    var config = crowi.getConfig()
+    var config = crowi.getConfig();
     return Config.isEnabledPlugins(config);
     return Config.isEnabledPlugins(config);
-  }
+  };
 
 
   locals.isEnabledLinebreaks = function() {
   locals.isEnabledLinebreaks = function() {
-    var config = crowi.getConfig()
+    var config = crowi.getConfig();
     return Config.isEnabledLinebreaks(config);
     return Config.isEnabledLinebreaks(config);
-  }
+  };
 
 
   locals.isEnabledLinebreaksInComments = function() {
   locals.isEnabledLinebreaksInComments = function() {
-    var config = crowi.getConfig()
+    var config = crowi.getConfig();
     return Config.isEnabledLinebreaksInComments(config);
     return Config.isEnabledLinebreaksInComments(config);
-  }
+  };
 
 
   locals.customCss = function() {
   locals.customCss = function() {
     return Config.customCss();
     return Config.customCss();
-  }
+  };
 
 
   locals.customScript = function() {
   locals.customScript = function() {
     return Config.customScript();
     return Config.customScript();
-  }
+  };
 
 
   locals.customHeader = function() {
   locals.customHeader = function() {
-    var config = crowi.getConfig()
+    var config = crowi.getConfig();
     return Config.customHeader(config);
     return Config.customHeader(config);
-  }
+  };
 
 
   locals.theme = function() {
   locals.theme = function() {
-    var config = crowi.getConfig()
+    var config = crowi.getConfig();
     return Config.theme(config);
     return Config.theme(config);
-  }
+  };
 
 
   locals.customTitle = function(page) {
   locals.customTitle = function(page) {
     const config = crowi.getConfig();
     const config = crowi.getConfig();
     return Config.customTitle(config, page);
     return Config.customTitle(config, page);
-  }
+  };
 
 
   locals.behaviorType = function() {
   locals.behaviorType = function() {
     var config = crowi.getConfig();
     var config = crowi.getConfig();
     return Config.behaviorType(config);
     return Config.behaviorType(config);
-  }
+  };
 
 
   locals.layoutType = function() {
   locals.layoutType = function() {
-    var config = crowi.getConfig()
+    var config = crowi.getConfig();
     return Config.layoutType(config);
     return Config.layoutType(config);
-  }
+  };
 
 
   locals.highlightJsStyle = function() {
   locals.highlightJsStyle = function() {
-    var config = crowi.getConfig()
+    var config = crowi.getConfig();
     return Config.highlightJsStyle(config);
     return Config.highlightJsStyle(config);
-  }
+  };
 
 
   locals.highlightJsStyleBorder = function() {
   locals.highlightJsStyleBorder = function() {
-    var config = crowi.getConfig()
+    var config = crowi.getConfig();
     return Config.highlightJsStyleBorder(config);
     return Config.highlightJsStyleBorder(config);
-  }
+  };
 
 
   locals.isEnabledTimeline = function() {
   locals.isEnabledTimeline = function() {
-    var config = crowi.getConfig()
+    var config = crowi.getConfig();
     return Config.isEnabledTimeline(config);
     return Config.isEnabledTimeline(config);
-  }
+  };
 
 
   locals.slackConfigured = function() {
   locals.slackConfigured = function() {
-    var config = crowi.getConfig()
+    var config = crowi.getConfig();
     if (Config.hasSlackToken(config) || Config.hasSlackIwhUrl(config)) {
     if (Config.hasSlackToken(config) || Config.hasSlackIwhUrl(config)) {
       return true;
       return true;
     }
     }
@@ -167,12 +169,12 @@ module.exports = function(crowi, app, req, locals) {
   };
   };
 
 
   locals.isUploadable = function() {
   locals.isUploadable = function() {
-    var config = crowi.getConfig()
+    var config = crowi.getConfig();
     return Config.isUploadable(config);
     return Config.isUploadable(config);
   };
   };
 
 
   locals.isEnabledAttachTitleHeader = function() {
   locals.isEnabledAttachTitleHeader = function() {
-    var config = crowi.getConfig()
+    var config = crowi.getConfig();
     return Config.isEnabledAttachTitleHeader(config);
     return Config.isEnabledAttachTitleHeader(config);
   };
   };
 
 
@@ -189,7 +191,7 @@ module.exports = function(crowi, app, req, locals) {
   };
   };
 
 
   locals.isUserPageList = function(path) {
   locals.isUserPageList = function(path) {
-    if (path.match(/^\/user\/[^\/]+\/$/)) {
+    if (path.match(/^\/user\/[^/]+\/$/)) {
       return true;
       return true;
     }
     }
 
 
@@ -229,7 +231,7 @@ module.exports = function(crowi, app, req, locals) {
   };
   };
 
 
   locals.css = {
   locals.css = {
-    grant: function (pageData) {
+    grant: function(pageData) {
       if (!pageData) {
       if (!pageData) {
         return '';
         return '';
       }
       }
@@ -249,7 +251,7 @@ module.exports = function(crowi, app, req, locals) {
       }
       }
       return '';
       return '';
     },
     },
-    userStatus: function (user) {
+    userStatus: function(user) {
       //debug('userStatus', user._id, user.usename, user.status);
       //debug('userStatus', user._id, user.usename, user.status);
 
 
       switch (user.status) {
       switch (user.status) {

+ 12 - 11
local_modules/crowi-fileupload-aws/index.js

@@ -9,14 +9,14 @@ module.exports = function(crowi) {
     , debug = require('debug')('growi:lib:fileUploaderAws')
     , debug = require('debug')('growi:lib:fileUploaderAws')
     , lib = {}
     , lib = {}
     , getAwsConfig = function() {
     , getAwsConfig = function() {
-        var config = crowi.getConfig();
-        return {
-          accessKeyId: config.crowi['aws:accessKeyId'],
-          secretAccessKey: config.crowi['aws:secretAccessKey'],
-          region: config.crowi['aws:region'],
-          bucket: config.crowi['aws:bucket']
-        };
+      var config = crowi.getConfig();
+      return {
+        accessKeyId: config.crowi['aws:accessKeyId'],
+        secretAccessKey: config.crowi['aws:secretAccessKey'],
+        region: config.crowi['aws:region'],
+        bucket: config.crowi['aws:bucket']
       };
       };
+    };
 
 
   function S3Factory() {
   function S3Factory() {
     const awsConfig = getAwsConfig();
     const awsConfig = getAwsConfig();
@@ -88,7 +88,7 @@ module.exports = function(crowi) {
     return url;
     return url;
   };
   };
 
 
-  lib.findDeliveryFile = function (fileId, filePath) {
+  lib.findDeliveryFile = function(fileId, filePath) {
     var cacheFile = lib.createCacheFileName(fileId);
     var cacheFile = lib.createCacheFileName(fileId);
 
 
     return new Promise((resolve, reject) => {
     return new Promise((resolve, reject) => {
@@ -102,7 +102,7 @@ module.exports = function(crowi) {
       var fileStream = fs.createWriteStream(cacheFile);
       var fileStream = fs.createWriteStream(cacheFile);
       var fileUrl = lib.generateUrl(filePath);
       var fileUrl = lib.generateUrl(filePath);
       debug('Load attachement file into local cache file', fileUrl, cacheFile);
       debug('Load attachement file into local cache file', fileUrl, cacheFile);
-      var request = loader.get(fileUrl, function(response) {
+      loader.get(fileUrl, function(response) {
         response.pipe(fileStream, { end: false });
         response.pipe(fileStream, { end: false });
         response.on('end', () => {
         response.on('end', () => {
           fileStream.end();
           fileStream.end();
@@ -130,7 +130,7 @@ module.exports = function(crowi) {
       debug('Failed to delete cache file (file may not exists).', err);
       debug('Failed to delete cache file (file may not exists).', err);
       // through
       // through
     });
     });
-  }
+  };
 
 
   // private
   // private
   lib.createCacheFileName = function(fileId) {
   lib.createCacheFileName = function(fileId) {
@@ -151,7 +151,8 @@ module.exports = function(crowi) {
         debug('Cache file found but the size is 0');
         debug('Cache file found but the size is 0');
         return true;
         return true;
       }
       }
-    } catch (e) {
+    }
+    catch (e) {
       // no such file or directory
       // no such file or directory
       debug('Stats error', e);
       debug('Stats error', e);
       return true;
       return true;

+ 4 - 4
resource/js/app.js

@@ -150,7 +150,7 @@ if (pageEditorElem) {
     if (componentInstances.page != null) {
     if (componentInstances.page != null) {
       componentInstances.page.setMarkdown(page.revision.body);
       componentInstances.page.setMarkdown(page.revision.body);
     }
     }
-  }
+  };
 
 
   pageEditor = ReactDOM.render(
   pageEditor = ReactDOM.render(
     <PageEditor crowi={crowi} crowiRenderer={crowiRenderer}
     <PageEditor crowi={crowi} crowiRenderer={crowiRenderer}
@@ -190,7 +190,7 @@ if (customCssEditorElem != null) {
   ReactDOM.render(
   ReactDOM.render(
     <CustomCssEditor inputElem={customCssInputElem} />,
     <CustomCssEditor inputElem={customCssInputElem} />,
     customCssEditorElem
     customCssEditorElem
-  )
+  );
 }
 }
 const customScriptEditorElem = document.getElementById('custom-script-editor');
 const customScriptEditorElem = document.getElementById('custom-script-editor');
 if (customScriptEditorElem != null) {
 if (customScriptEditorElem != null) {
@@ -200,7 +200,7 @@ if (customScriptEditorElem != null) {
   ReactDOM.render(
   ReactDOM.render(
     <CustomScriptEditor inputElem={customScriptInputElem} />,
     <CustomScriptEditor inputElem={customScriptInputElem} />,
     customScriptEditorElem
     customScriptEditorElem
-  )
+  );
 }
 }
 const customHeaderEditorElem = document.getElementById('custom-header-editor');
 const customHeaderEditorElem = document.getElementById('custom-header-editor');
 if (customHeaderEditorElem != null) {
 if (customHeaderEditorElem != null) {
@@ -210,7 +210,7 @@ if (customHeaderEditorElem != null) {
   ReactDOM.render(
   ReactDOM.render(
     <CustomHeaderEditor inputElem={customHeaderInputElem} />,
     <CustomHeaderEditor inputElem={customHeaderInputElem} />,
     customHeaderEditorElem
     customHeaderEditorElem
-  )
+  );
 }
 }
 
 
 // うわーもうー (commented by Crowi team -- 2018.03.23 Yuki Takei)
 // うわーもうー (commented by Crowi team -- 2018.03.23 Yuki Takei)

+ 2 - 2
resource/js/components/Admin/CustomCssEditor.js

@@ -35,7 +35,7 @@ export default class CustomCssEditor extends React.Component {
           autoRefresh: true,
           autoRefresh: true,
           matchBrackets: true,
           matchBrackets: true,
           autoCloseBrackets: true,
           autoCloseBrackets: true,
-          extraKeys: {"Ctrl-Space": "autocomplete"},
+          extraKeys: {'Ctrl-Space': 'autocomplete'},
         }}
         }}
         editorDidMount={(editor, next) => {
         editorDidMount={(editor, next) => {
           // resizable with jquery.ui
           // resizable with jquery.ui
@@ -49,7 +49,7 @@ export default class CustomCssEditor extends React.Component {
           this.props.inputElem.value = value;
           this.props.inputElem.value = value;
         }}
         }}
       />
       />
-    )
+    );
   }
   }
 
 
 }
 }

+ 2 - 2
resource/js/components/Admin/CustomHeaderEditor.js

@@ -33,7 +33,7 @@ export default class CustomHeaderEditor extends React.Component {
           autoRefresh: true,
           autoRefresh: true,
           matchBrackets: true,
           matchBrackets: true,
           autoCloseBrackets: true,
           autoCloseBrackets: true,
-          extraKeys: {"Ctrl-Space": "autocomplete"},
+          extraKeys: {'Ctrl-Space': 'autocomplete'},
         }}
         }}
         editorDidMount={(editor, next) => {
         editorDidMount={(editor, next) => {
           // resizable with jquery.ui
           // resizable with jquery.ui
@@ -47,7 +47,7 @@ export default class CustomHeaderEditor extends React.Component {
           this.props.inputElem.value = value;
           this.props.inputElem.value = value;
         }}
         }}
       />
       />
-    )
+    );
   }
   }
 
 
 }
 }

+ 2 - 2
resource/js/components/Admin/CustomScriptEditor.js

@@ -35,7 +35,7 @@ export default class CustomScriptEditor extends React.Component {
           autoRefresh: true,
           autoRefresh: true,
           matchBrackets: true,
           matchBrackets: true,
           autoCloseBrackets: true,
           autoCloseBrackets: true,
-          extraKeys: {"Ctrl-Space": "autocomplete"},
+          extraKeys: {'Ctrl-Space': 'autocomplete'},
         }}
         }}
         editorDidMount={(editor, next) => {
         editorDidMount={(editor, next) => {
           // resizable with jquery.ui
           // resizable with jquery.ui
@@ -49,7 +49,7 @@ export default class CustomScriptEditor extends React.Component {
           this.props.inputElem.value = value;
           this.props.inputElem.value = value;
         }}
         }}
       />
       />
-    )
+    );
   }
   }
 
 
 }
 }

+ 3 - 3
resource/js/components/PageEditor/PasteHelper.js

@@ -1,4 +1,4 @@
-import accepts from 'attr-accept'
+import accepts from 'attr-accept';
 
 
 import markdownListUtil from './MarkdownListUtil';
 import markdownListUtil from './MarkdownListUtil';
 
 
@@ -33,7 +33,7 @@ class PasteHelper {
    * @param {*} accept
    * @param {*} accept
    */
    */
   fileAccepted(file, accept) {
   fileAccepted(file, accept) {
-    return file.type === 'application/x-moz-file' || accepts(file, accept)
+    return file.type === 'application/x-moz-file' || accepts(file, accept);
   }
   }
   /**
   /**
    * transplanted from react-dropzone
    * transplanted from react-dropzone
@@ -44,7 +44,7 @@ class PasteHelper {
    * @param {number} minSize
    * @param {number} minSize
    */
    */
   fileMatchSize(file, maxSize, minSize) {
   fileMatchSize(file, maxSize, minSize) {
-    return file.size <= maxSize && file.size >= minSize
+    return file.size <= maxSize && file.size >= minSize;
   }
   }
 }
 }