Ver código fonte

WIP: apply to src/server/models

Yuki Takei 7 anos atrás
pai
commit
96ffc3f735

+ 2 - 1
src/server/models/GlobalNotificationSetting/GlobalNotificationMailSetting.js

@@ -1,5 +1,6 @@
 const mongoose = require('mongoose');
 const mongoose = require('mongoose');
 const GlobalNotificationSetting = require('./index');
 const GlobalNotificationSetting = require('./index');
+
 const GlobalNotificationSettingClass = GlobalNotificationSetting.class;
 const GlobalNotificationSettingClass = GlobalNotificationSetting.class;
 const GlobalNotificationSettingSchema = GlobalNotificationSetting.schema;
 const GlobalNotificationSettingSchema = GlobalNotificationSetting.schema;
 
 
@@ -10,7 +11,7 @@ module.exports = function(crowi) {
   const GlobalNotificationSettingModel = mongoose.model('GlobalNotificationSetting', GlobalNotificationSettingSchema);
   const GlobalNotificationSettingModel = mongoose.model('GlobalNotificationSetting', GlobalNotificationSettingSchema);
   const GlobalNotificationMailSettingModel = GlobalNotificationSettingModel.discriminator('mail', new mongoose.Schema({
   const GlobalNotificationMailSettingModel = GlobalNotificationSettingModel.discriminator('mail', new mongoose.Schema({
     toEmail: String,
     toEmail: String,
-  }, {discriminatorKey: 'type'}));
+  }, { discriminatorKey: 'type' }));
 
 
   return GlobalNotificationMailSettingModel;
   return GlobalNotificationMailSettingModel;
 };
 };

+ 2 - 1
src/server/models/GlobalNotificationSetting/GlobalNotificationSlackSetting.js

@@ -1,5 +1,6 @@
 const mongoose = require('mongoose');
 const mongoose = require('mongoose');
 const GlobalNotificationSetting = require('./index');
 const GlobalNotificationSetting = require('./index');
+
 const GlobalNotificationSettingClass = GlobalNotificationSetting.class;
 const GlobalNotificationSettingClass = GlobalNotificationSetting.class;
 const GlobalNotificationSettingSchema = GlobalNotificationSetting.schema;
 const GlobalNotificationSettingSchema = GlobalNotificationSetting.schema;
 
 
@@ -10,7 +11,7 @@ module.exports = function(crowi) {
   const GlobalNotificationSettingModel = mongoose.model('GlobalNotificationSetting', GlobalNotificationSettingSchema);
   const GlobalNotificationSettingModel = mongoose.model('GlobalNotificationSetting', GlobalNotificationSettingSchema);
   const GlobalNotificationSlackSettingModel = GlobalNotificationSettingModel.discriminator('slack', new mongoose.Schema({
   const GlobalNotificationSlackSettingModel = GlobalNotificationSettingModel.discriminator('slack', new mongoose.Schema({
     slackChannels: String,
     slackChannels: String,
-  }, {discriminatorKey: 'type'}));
+  }, { discriminatorKey: 'type' }));
 
 
   return GlobalNotificationSlackSettingModel;
   return GlobalNotificationSlackSettingModel;
 };
 };

+ 27 - 29
src/server/models/GlobalNotificationSetting/index.js

@@ -11,12 +11,34 @@ const globalNotificationSettingSchema = new mongoose.Schema({
 });
 });
 
 
 
 
+const generatePathsOnTree = (path, pathList) => {
+  pathList.push(path);
+
+  if (path === '/') {
+    return pathList;
+  }
+
+  const newPath = nodePath.posix.dirname(path);
+
+  return generatePathsOnTree(newPath, pathList);
+};
+
+const generatePathsToMatch = (originalPath) => {
+  const pathList = generatePathsOnTree(originalPath, []);
+  return pathList.map((path) => {
+    if (path !== originalPath) {
+      return `${path}/*`;
+    }
+
+    return path;
+  });
+};
+
 /**
 /**
  * GlobalNotificationSetting Class
  * GlobalNotificationSetting Class
  * @class GlobalNotificationSetting
  * @class GlobalNotificationSetting
  */
  */
 class GlobalNotificationSetting {
 class GlobalNotificationSetting {
-
   constructor(crowi) {
   constructor(crowi) {
     this.crowi = crowi;
     this.crowi = crowi;
   }
   }
@@ -26,7 +48,7 @@ class GlobalNotificationSetting {
    * @param {string} id
    * @param {string} id
    */
    */
   static async enable(id) {
   static async enable(id) {
-    const setting = await this.findOne({_id: id});
+    const setting = await this.findOne({ _id: id });
 
 
     setting.isEnabled = true;
     setting.isEnabled = true;
     setting.save();
     setting.save();
@@ -39,7 +61,7 @@ class GlobalNotificationSetting {
    * @param {string} id
    * @param {string} id
    */
    */
   static async disable(id) {
   static async disable(id) {
-    const setting = await this.findOne({_id: id});
+    const setting = await this.findOne({ _id: id });
 
 
     setting.isEnabled = false;
     setting.isEnabled = false;
     setting.save();
     setting.save();
@@ -65,9 +87,9 @@ class GlobalNotificationSetting {
     const pathsToMatch = generatePathsToMatch(path);
     const pathsToMatch = generatePathsToMatch(path);
 
 
     const settings = await this.find({
     const settings = await this.find({
-      triggerPath: {$in: pathsToMatch},
+      triggerPath: { $in: pathsToMatch },
       triggerEvents: event,
       triggerEvents: event,
-      isEnabled: true
+      isEnabled: true,
     })
     })
     .sort({ triggerPath: 1 });
     .sort({ triggerPath: 1 });
 
 
@@ -75,30 +97,6 @@ class GlobalNotificationSetting {
   }
   }
 }
 }
 
 
-const generatePathsOnTree = (path, pathList) => {
-  pathList.push(path);
-
-  if (path === '/') {
-    return pathList;
-  }
-
-  const newPath = nodePath.posix.dirname(path);
-
-  return generatePathsOnTree(newPath, pathList);
-};
-
-const generatePathsToMatch = (originalPath) => {
-  const pathList = generatePathsOnTree(originalPath, []);
-  return pathList.map(path => {
-    if (path !== originalPath) {
-      return path + '/*';
-    }
-    else {
-      return path;
-    }
-  });
-};
-
 
 
 module.exports = {
 module.exports = {
   class: GlobalNotificationSetting,
   class: GlobalNotificationSetting,

+ 18 - 17
src/server/models/attachment.js

@@ -2,6 +2,7 @@
 /* eslint-disable no-return-await */
 /* eslint-disable no-return-await */
 
 
 const debug = require('debug')('growi:models:attachment');
 const debug = require('debug')('growi:models:attachment');
+// eslint-disable-next-line no-unused-vars
 const logger = require('@alias/logger')('growi:models:attachment');
 const logger = require('@alias/logger')('growi:models:attachment');
 const path = require('path');
 const path = require('path');
 
 
@@ -12,8 +13,6 @@ const ObjectId = mongoose.Schema.Types.ObjectId;
 module.exports = function(crowi) {
 module.exports = function(crowi) {
   const fileUploader = require('../service/file-uploader')(crowi);
   const fileUploader = require('../service/file-uploader')(crowi);
 
 
-  let attachmentSchema;
-
   function generateFileHash(fileName) {
   function generateFileHash(fileName) {
     const hash = require('crypto').createHash('md5');
     const hash = require('crypto').createHash('md5');
     hash.update(`${fileName}_${Date.now()}`);
     hash.update(`${fileName}_${Date.now()}`);
@@ -21,8 +20,7 @@ module.exports = function(crowi) {
     return hash.digest('hex');
     return hash.digest('hex');
   }
   }
 
 
-
-  attachmentSchema = new mongoose.Schema({
+  const attachmentSchema = new mongoose.Schema({
     page: { type: ObjectId, ref: 'Page', index: true },
     page: { type: ObjectId, ref: 'Page', index: true },
     creator: { type: ObjectId, ref: 'User', index: true },
     creator: { type: ObjectId, ref: 'User', index: true },
     filePath: { type: String }, // DEPRECATED: remains for backward compatibility for v3.3.x or below
     filePath: { type: String }, // DEPRECATED: remains for backward compatibility for v3.3.x or below
@@ -76,19 +74,22 @@ module.exports = function(crowi) {
 
 
     return new Promise((resolve, reject) => {
     return new Promise((resolve, reject) => {
       Attachment.find({ page: pageId })
       Attachment.find({ page: pageId })
-      .then((attachments) => {
-        for (const attachment of attachments) {
-          Attachment.removeWithSubstanceById(attachment._id).then((res) => {
-            // do nothing
-          }).catch((err) => {
-            debug('Attachment remove error', err);
-          });
-        }
-
-        resolve(attachments);
-      }).catch((err) => {
-        reject(err);
-      });
+        .then((attachments) => {
+          for (const attachment of attachments) {
+            Attachment.removeWithSubstanceById(attachment._id)
+              .then((res) => {
+                // do nothing
+              })
+              .catch((err) => {
+                debug('Attachment remove error', err);
+              });
+          }
+
+          resolve(attachments);
+        })
+        .catch((err) => {
+          reject(err);
+        });
     });
     });
   };
   };
 
 

+ 5 - 9
src/server/models/comment.js

@@ -5,8 +5,6 @@ module.exports = function(crowi) {
   const debug = require('debug')('growi:models:comment');
   const debug = require('debug')('growi:models:comment');
   const mongoose = require('mongoose');
   const mongoose = require('mongoose');
   const ObjectId = mongoose.Schema.Types.ObjectId;
   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({
   const commentSchema = new mongoose.Schema({
     page: { type: ObjectId, ref: 'Page', index: true },
     page: { type: ObjectId, ref: 'Page', index: true },
@@ -20,7 +18,6 @@ module.exports = function(crowi) {
 
 
   commentSchema.statics.create = function(pageId, creatorId, revisionId, comment, position, isMarkdown) {
   commentSchema.statics.create = function(pageId, creatorId, revisionId, comment, position, isMarkdown) {
     const Comment = this;
     const Comment = this;
-    const commentPosition = position || -1;
 
 
     return new Promise(((resolve, reject) => {
     return new Promise(((resolve, reject) => {
       const newComment = new Comment();
       const newComment = new Comment();
@@ -85,13 +82,12 @@ module.exports = function(crowi) {
   commentSchema.post('save', (savedComment) => {
   commentSchema.post('save', (savedComment) => {
     const Page = crowi.model('Page');
     const Page = crowi.model('Page');
 
 
-
-    const Comment = crowi.model('Comment');
     Page.updateCommentCount(savedComment.page)
     Page.updateCommentCount(savedComment.page)
-    .then((page) => {
-      debug('CommentCount Updated', page);
-    }).catch(() => {
-    });
+      .then((page) => {
+        debug('CommentCount Updated', page);
+      })
+      .catch(() => {
+      });
   });
   });
 
 
   return mongoose.model('Comment', commentSchema);
   return mongoose.model('Comment', commentSchema);

+ 1 - 1
src/server/models/page-group-relation.js

@@ -242,7 +242,7 @@ class PageGroupRelation {
     return this.findById(id)
     return this.findById(id)
       .then((relationData) => {
       .then((relationData) => {
         if (relationData == null) {
         if (relationData == null) {
-          throw new Exception('PageGroupRelation data is not exists. id:', id);
+          throw new Error('PageGroupRelation data is not exists. id:', id);
         }
         }
         else {
         else {
           relationData.remove();
           relationData.remove();

+ 22 - 16
src/server/models/page.js

@@ -1,6 +1,8 @@
 // disable no-return-await for model functions
 // disable no-return-await for model functions
 /* eslint-disable no-return-await */
 /* eslint-disable no-return-await */
 
 
+/* eslint-disable no-use-before-define */
+
 const debug = require('debug')('growi:models:page');
 const debug = require('debug')('growi:models:page');
 const nodePath = require('path');
 const nodePath = require('path');
 const mongoose = require('mongoose');
 const mongoose = require('mongoose');
@@ -141,6 +143,7 @@ class PageQueryBuilder {
    */
    */
   addConditionToListWithDescendants(path, option) {
   addConditionToListWithDescendants(path, option) {
     // ignore other pages than descendants
     // ignore other pages than descendants
+    // eslint-disable-next-line no-param-reassign
     path = addSlashOfEnd(path);
     path = addSlashOfEnd(path);
 
 
     // add option to escape the regex strings
     // add option to escape the regex strings
@@ -239,7 +242,7 @@ class PageQueryBuilder {
 
 
   addConditionToPagenate(offset, limit, sortOpt) {
   addConditionToPagenate(offset, limit, sortOpt) {
     this.query = this.query
     this.query = this.query
-      .sort(sortOpt).skip(offset).limit(limit);
+      .sort(sortOpt).skip(offset).limit(limit); // eslint-disable-line newline-per-chained-call
 
 
     return this;
     return this;
   }
   }
@@ -289,7 +292,7 @@ module.exports = function(crowi) {
   };
   };
 
 
   pageSchema.methods.isPublic = function() {
   pageSchema.methods.isPublic = function() {
-    if (!this.grant || this.grant == GRANT_PUBLIC) {
+    if (!this.grant || this.grant === GRANT_PUBLIC) {
       return true;
       return true;
     }
     }
 
 
@@ -378,12 +381,12 @@ module.exports = function(crowi) {
       return true;
       return true;
     }
     }
 
 
-    return (this.latestRevision == this.revision._id.toString());
+    return (this.latestRevision === this.revision._id.toString());
   };
   };
 
 
   pageSchema.methods.isUpdatable = function(previousRevision) {
   pageSchema.methods.isUpdatable = function(previousRevision) {
     const revision = this.latestRevision || this.revision;
     const revision = this.latestRevision || this.revision;
-    if (revision != previousRevision) {
+    if (revision !== previousRevision) {
       return false;
       return false;
     }
     }
     return true;
     return true;
@@ -391,13 +394,12 @@ module.exports = function(crowi) {
 
 
   pageSchema.methods.isLiked = function(userData) {
   pageSchema.methods.isLiked = function(userData) {
     return this.liker.some((likedUser) => {
     return this.liker.some((likedUser) => {
-      return likedUser == userData._id.toString();
+      return likedUser === userData._id.toString();
     });
     });
   };
   };
 
 
   pageSchema.methods.like = function(userData) {
   pageSchema.methods.like = function(userData) {
     const self = this;
     const self = this;
-    const Page = self;
 
 
     return new Promise(((resolve, reject) => {
     return new Promise(((resolve, reject) => {
       const added = self.liker.addToSet(userData._id);
       const added = self.liker.addToSet(userData._id);
@@ -419,12 +421,11 @@ module.exports = function(crowi) {
 
 
   pageSchema.methods.unlike = function(userData, callback) {
   pageSchema.methods.unlike = function(userData, callback) {
     const self = this;
     const self = this;
-    const Page = self;
 
 
     return new Promise(((resolve, reject) => {
     return new Promise(((resolve, reject) => {
       const beforeCount = self.liker.length;
       const beforeCount = self.liker.length;
       self.liker.pull(userData._id);
       self.liker.pull(userData._id);
-      if (self.liker.length != beforeCount) {
+      if (self.liker.length !== beforeCount) {
         self.save((err, data) => {
         self.save((err, data) => {
           if (err) {
           if (err) {
             return reject(err);
             return reject(err);
@@ -565,6 +566,7 @@ module.exports = function(crowi) {
 
 
   pageSchema.statics.getDeletedPageName = function(path) {
   pageSchema.statics.getDeletedPageName = function(path) {
     if (path.match('/')) {
     if (path.match('/')) {
+      // eslint-disable-next-line no-param-reassign
       path = path.substr(1);
       path = path.substr(1);
     }
     }
     return `/trash/${path}`;
     return `/trash/${path}`;
@@ -988,11 +990,11 @@ module.exports = function(crowi) {
   }
   }
 
 
   async function validateAppliedScope(user, grant, grantUserGroupId) {
   async function validateAppliedScope(user, grant, grantUserGroupId) {
-    if (grant == GRANT_USER_GROUP && grantUserGroupId == null) {
+    if (grant === GRANT_USER_GROUP && grantUserGroupId == null) {
       throw new Error('grant userGroupId is not specified');
       throw new Error('grant userGroupId is not specified');
     }
     }
 
 
-    if (grant == GRANT_USER_GROUP) {
+    if (grant === GRANT_USER_GROUP) {
       const UserGroupRelation = crowi.model('UserGroupRelation');
       const UserGroupRelation = crowi.model('UserGroupRelation');
       const count = await UserGroupRelation.countByGroupIdAndUser(grantUserGroupId, user);
       const count = await UserGroupRelation.countByGroupIdAndUser(grantUserGroupId, user);
 
 
@@ -1013,7 +1015,7 @@ module.exports = function(crowi) {
     const socketClientId = options.socketClientId || null;
     const socketClientId = options.socketClientId || null;
 
 
     // sanitize path
     // sanitize path
-    path = crowi.xss.process(path);
+    path = crowi.xss.process(path); // eslint-disable-line no-param-reassign
 
 
     let grant = options.grant || GRANT_PUBLIC;
     let grant = options.grant || GRANT_PUBLIC;
     // force public
     // force public
@@ -1040,7 +1042,9 @@ module.exports = function(crowi) {
     let savedPage = await page.save();
     let savedPage = await page.save();
     const newRevision = Revision.prepareRevision(savedPage, body, null, user, { format });
     const newRevision = Revision.prepareRevision(savedPage, body, null, user, { format });
     const revision = await pushRevision(savedPage, newRevision, user, grant, grantUserGroupId);
     const revision = await pushRevision(savedPage, newRevision, user, grant, grantUserGroupId);
-    savedPage = await this.findByPath(revision.path).populate('revision').populate('creator');
+    savedPage = await this.findByPath(revision.path)
+      .populate('revision')
+      .populate('creator');
 
 
     if (socketClientId != null) {
     if (socketClientId != null) {
       pageEvent.emit('create', savedPage, user, socketClientId);
       pageEvent.emit('create', savedPage, user, socketClientId);
@@ -1064,7 +1068,9 @@ module.exports = function(crowi) {
     let savedPage = await pageData.save();
     let savedPage = await pageData.save();
     const newRevision = await Revision.prepareRevision(pageData, body, previousBody, user);
     const newRevision = await Revision.prepareRevision(pageData, body, previousBody, user);
     const revision = await pushRevision(savedPage, newRevision, user, grant, grantUserGroupId);
     const revision = await pushRevision(savedPage, newRevision, user, grant, grantUserGroupId);
-    savedPage = await this.findByPath(revision.path).populate('revision').populate('creator');
+    savedPage = await this.findByPath(revision.path)
+      .populate('revision')
+      .populate('creator');
 
 
     if (isSyncRevisionToHackmd) {
     if (isSyncRevisionToHackmd) {
       savedPage = await this.syncRevisionToHackmd(savedPage);
       savedPage = await this.syncRevisionToHackmd(savedPage);
@@ -1118,7 +1124,7 @@ module.exports = function(crowi) {
       return updatedPageData;
       return updatedPageData;
     }
     }
 
 
-    return Promise.reject('Page is not deletable.');
+    return Promise.reject(new Error('Page is not deletable.'));
   };
   };
 
 
   const checkIfTrashed = (path) => {
   const checkIfTrashed = (path) => {
@@ -1277,7 +1283,7 @@ module.exports = function(crowi) {
     const socketClientId = options.socketClientId || null;
     const socketClientId = options.socketClientId || null;
 
 
     // sanitize path
     // sanitize path
-    newPagePath = crowi.xss.process(newPagePath);
+    newPagePath = crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
 
 
     // update Page
     // update Page
     pageData.path = newPagePath;
     pageData.path = newPagePath;
@@ -1306,7 +1312,7 @@ module.exports = function(crowi) {
     const pathRegExp = new RegExp(`^${escapeStringRegexp(path)}`, 'i');
     const pathRegExp = new RegExp(`^${escapeStringRegexp(path)}`, 'i');
 
 
     // sanitize path
     // sanitize path
-    newPagePathPrefix = crowi.xss.process(newPagePathPrefix);
+    newPagePathPrefix = crowi.xss.process(newPagePathPrefix); // eslint-disable-line no-param-reassign
 
 
     const result = await this.findListWithDescendants(path, user, options);
     const result = await this.findListWithDescendants(path, user, options);
     await Promise.all(result.pages.map((page) => {
     await Promise.all(result.pages.map((page) => {

+ 14 - 17
src/server/models/user-group-relation.js

@@ -1,6 +1,7 @@
 const debug = require('debug')('growi:models:userGroupRelation');
 const debug = require('debug')('growi:models:userGroupRelation');
 const mongoose = require('mongoose');
 const mongoose = require('mongoose');
 const mongoosePaginate = require('mongoose-paginate');
 const mongoosePaginate = require('mongoose-paginate');
+
 const ObjectId = mongoose.Schema.Types.ObjectId;
 const ObjectId = mongoose.Schema.Types.ObjectId;
 
 
 
 
@@ -20,7 +21,6 @@ schema.plugin(mongoosePaginate);
  * @class UserGroupRelation
  * @class UserGroupRelation
  */
  */
 class UserGroupRelation {
 class UserGroupRelation {
-
   /**
   /**
    * limit items num for pagination
    * limit items num for pagination
    *
    *
@@ -49,15 +49,15 @@ class UserGroupRelation {
    */
    */
   static removeAllInvalidRelations() {
   static removeAllInvalidRelations() {
     return this.findAllRelation()
     return this.findAllRelation()
-      .then(relations => {
+      .then((relations) => {
         // filter invalid documents
         // filter invalid documents
-        return relations.filter(relation => {
+        return relations.filter((relation) => {
           return relation.relatedUser == null || relation.relatedGroup == null;
           return relation.relatedUser == null || relation.relatedGroup == null;
         });
         });
       })
       })
-      .then(invalidRelations => {
-        const ids = invalidRelations.map(relation => relation._id);
-        return this.deleteMany({ _id: { $in: ids }});
+      .then((invalidRelations) => {
+        const ids = invalidRelations.map((relation) => { return relation._id });
+        return this.deleteMany({ _id: { $in: ids } });
       });
       });
   }
   }
 
 
@@ -69,7 +69,6 @@ class UserGroupRelation {
    * @memberof UserGroupRelation
    * @memberof UserGroupRelation
    */
    */
   static findAllRelation() {
   static findAllRelation() {
-
     return this
     return this
       .find()
       .find()
       .populate('relatedUser')
       .populate('relatedUser')
@@ -121,8 +120,8 @@ class UserGroupRelation {
       .find({ relatedUser: user.id })
       .find({ relatedUser: user.id })
       .populate('relatedGroup')
       .populate('relatedGroup')
       // filter documents only relatedGroup is not null
       // filter documents only relatedGroup is not null
-      .then(userGroupRelations => {
-        return userGroupRelations.filter(relation => {
+      .then((userGroupRelations) => {
+        return userGroupRelations.filter((relation) => {
           return relation.relatedGroup != null;
           return relation.relatedGroup != null;
         });
         });
       });
       });
@@ -140,7 +139,7 @@ class UserGroupRelation {
       .select('relatedGroup')
       .select('relatedGroup')
       .exec();
       .exec();
 
 
-    return relations.map(relation => relation.relatedGroup);
+    return relations.map((relation) => { return relation.relatedGroup });
   }
   }
 
 
   /**
   /**
@@ -181,7 +180,7 @@ class UserGroupRelation {
   static async countByGroupIdAndUser(userGroupId, userData) {
   static async countByGroupIdAndUser(userGroupId, userData) {
     const query = {
     const query = {
       relatedGroup: userGroupId,
       relatedGroup: userGroupId,
-      relatedUser: userData.id
+      relatedUser: userData.id,
     };
     };
 
 
     return this.count(query);
     return this.count(query);
@@ -222,7 +221,7 @@ class UserGroupRelation {
   static isRelatedUserForGroup(userData, userGroup) {
   static isRelatedUserForGroup(userData, userGroup) {
     const query = {
     const query = {
       relatedGroup: userGroup.id,
       relatedGroup: userGroup.id,
-      relatedUser: userData.id
+      relatedUser: userData.id,
     };
     };
 
 
     return this
     return this
@@ -230,7 +229,7 @@ class UserGroupRelation {
       .exec()
       .exec()
       .then((count) => {
       .then((count) => {
         // return true or false of the relation is exists(not count)
         // return true or false of the relation is exists(not count)
-        return (0 < count);
+        return (count > 0);
       });
       });
   }
   }
 
 
@@ -246,7 +245,7 @@ class UserGroupRelation {
   static createRelation(userGroup, user) {
   static createRelation(userGroup, user) {
     return this.create({
     return this.create({
       relatedGroup: userGroup.id,
       relatedGroup: userGroup.id,
-      relatedUser: user.id
+      relatedUser: user.id,
     });
     });
   }
   }
 
 
@@ -271,18 +270,16 @@ class UserGroupRelation {
    * @memberof UserGroupRelation
    * @memberof UserGroupRelation
    */
    */
   static removeById(id) {
   static removeById(id) {
-
     return this.findById(id)
     return this.findById(id)
       .then((relationData) => {
       .then((relationData) => {
         if (relationData == null) {
         if (relationData == null) {
-          throw new Exception('UserGroupRelation data is not exists. id:', id);
+          throw new Error('UserGroupRelation data is not exists. id:', id);
         }
         }
         else {
         else {
           relationData.remove();
           relationData.remove();
         }
         }
       });
       });
   }
   }
-
 }
 }
 
 
 module.exports = function(crowi) {
 module.exports = function(crowi) {

+ 8 - 12
src/server/models/user-group.js

@@ -14,7 +14,6 @@ const schema = new mongoose.Schema({
 schema.plugin(mongoosePaginate);
 schema.plugin(mongoosePaginate);
 
 
 class UserGroup {
 class UserGroup {
-
   /**
   /**
    * public fields for UserGroup model
    * public fields for UserGroup model
    *
    *
@@ -43,14 +42,13 @@ class UserGroup {
 
 
   // グループ画像パスの生成
   // グループ画像パスの生成
   static createUserGroupPictureFilePath(userGroup, name) {
   static createUserGroupPictureFilePath(userGroup, name) {
-    var ext = '.' + name.match(/(.*)(?:\.([^.]+$))/)[2];
+    const ext = `.${name.match(/(.*)(?:\.([^.]+$))/)[2]}`;
 
 
-    return 'userGroup/' + userGroup._id + ext;
+    return `userGroup/${userGroup._id}${ext}`;
   }
   }
 
 
   // すべてのグループを取得(オプション指定可)
   // すべてのグループを取得(オプション指定可)
   static findAllGroups(option) {
   static findAllGroups(option) {
-
     return this.find().exec();
     return this.find().exec();
   }
   }
 
 
@@ -82,7 +80,7 @@ class UserGroup {
 
 
   // 登録可能グループ名確認
   // 登録可能グループ名確認
   static isRegisterableName(name) {
   static isRegisterableName(name) {
-    const query = { name: name };
+    const query = { name };
 
 
     return this.findOne(query)
     return this.findOne(query)
       .then((userGroupData) => {
       .then((userGroupData) => {
@@ -95,15 +93,15 @@ class UserGroup {
     const PageGroupRelation = mongoose.model('PageGroupRelation');
     const PageGroupRelation = mongoose.model('PageGroupRelation');
     const UserGroupRelation = mongoose.model('UserGroupRelation');
     const UserGroupRelation = mongoose.model('UserGroupRelation');
 
 
-    let removed = undefined;
+    let removed;
     return this.findById(id)
     return this.findById(id)
-      .then(userGroupData => {
+      .then((userGroupData) => {
         if (userGroupData == null) {
         if (userGroupData == null) {
-          throw new Exception('UserGroup data is not exists. id:', id);
+          throw new Error('UserGroup data is not exists. id:', id);
         }
         }
         return userGroupData.remove();
         return userGroupData.remove();
       })
       })
-      .then(removedUserGroupData => {
+      .then((removedUserGroupData) => {
         removed = removedUserGroupData;
         removed = removedUserGroupData;
       })
       })
       // remove relations
       // remove relations
@@ -120,7 +118,7 @@ class UserGroup {
 
 
   // グループ生成(名前が要る)
   // グループ生成(名前が要る)
   static createGroupByName(name) {
   static createGroupByName(name) {
-    return this.create({name: name});
+    return this.create({ name });
   }
   }
 
 
   // グループ名の更新
   // グループ名の更新
@@ -129,7 +127,6 @@ class UserGroup {
     this.name = name;
     this.name = name;
     return this.save();
     return this.save();
   }
   }
-
 }
 }
 
 
 
 
@@ -138,4 +135,3 @@ module.exports = function(crowi) {
   schema.loadClass(UserGroup);
   schema.loadClass(UserGroup);
   return mongoose.model('UserGroup', schema);
   return mongoose.model('UserGroup', schema);
 };
 };
-

+ 156 - 147
src/server/models/user.js

@@ -1,30 +1,32 @@
+/* eslint-disable no-use-before-define */
+
 const debug = require('debug')('growi:models:user');
 const debug = require('debug')('growi:models:user');
 const logger = require('@alias/logger')('growi:models:user');
 const logger = require('@alias/logger')('growi:models:user');
 const path = require('path');
 const path = require('path');
 const mongoose = require('mongoose');
 const mongoose = require('mongoose');
 const uniqueValidator = require('mongoose-unique-validator');
 const uniqueValidator = require('mongoose-unique-validator');
 const mongoosePaginate = require('mongoose-paginate');
 const mongoosePaginate = require('mongoose-paginate');
+
 const ObjectId = mongoose.Schema.Types.ObjectId;
 const ObjectId = mongoose.Schema.Types.ObjectId;
 const crypto = require('crypto');
 const crypto = require('crypto');
 const async = require('async');
 const async = require('async');
 
 
 module.exports = function(crowi) {
 module.exports = function(crowi) {
   const STATUS_REGISTERED = 1;
   const STATUS_REGISTERED = 1;
-  const STATUS_ACTIVE     = 2;
-  const STATUS_SUSPENDED  = 3;
-  const STATUS_DELETED    = 4;
-  const STATUS_INVITED    = 5;
+  const STATUS_ACTIVE = 2;
+  const STATUS_SUSPENDED = 3;
+  const STATUS_DELETED = 4;
+  const STATUS_INVITED = 5;
   const USER_PUBLIC_FIELDS = '_id image isEmailPublished isGravatarEnabled googleId name username email introduction status lang createdAt admin';
   const USER_PUBLIC_FIELDS = '_id image isEmailPublished isGravatarEnabled googleId name username email introduction status lang createdAt admin';
   const IMAGE_POPULATION = { path: 'imageAttachment', select: 'filePathProxied' };
   const IMAGE_POPULATION = { path: 'imageAttachment', select: 'filePathProxied' };
 
 
-  const LANG_EN    = 'en';
+  const LANG_EN = 'en';
   const LANG_EN_US = 'en-US';
   const LANG_EN_US = 'en-US';
   const LANG_EN_GB = 'en-GB';
   const LANG_EN_GB = 'en-GB';
-  const LANG_JA    = 'ja';
+  const LANG_JA = 'ja';
 
 
   const PAGE_ITEMS = 50;
   const PAGE_ITEMS = 50;
 
 
-  let userSchema;
   let userEvent;
   let userEvent;
 
 
   // init event
   // init event
@@ -33,7 +35,7 @@ module.exports = function(crowi) {
     userEvent.on('activated', userEvent.onActivated);
     userEvent.on('activated', userEvent.onActivated);
   }
   }
 
 
-  userSchema = new mongoose.Schema({
+  const userSchema = new mongoose.Schema({
     userId: String,
     userId: String,
     image: String,
     image: String,
     imageAttachment: { type: ObjectId, ref: 'Attachment' },
     imageAttachment: { type: ObjectId, ref: 'Attachment' },
@@ -43,23 +45,26 @@ module.exports = function(crowi) {
     name: { type: String },
     name: { type: String },
     username: { type: String, required: true, unique: true },
     username: { type: String, required: true, unique: true },
     email: { type: String, unique: true, sparse: true },
     email: { type: String, unique: true, sparse: true },
-    //// The official settings
+    // === The official settings
     // username: { type: String, index: true },
     // username: { type: String, index: true },
     // email: { type: String, required: true, index: true },
     // email: { type: String, required: true, index: true },
-    //// crowi-plus (>= 2.1.0, <2.3.0) settings
+    // === crowi-plus (>= 2.1.0, <2.3.0) settings
     // email: { type: String, required: true, unique: true },
     // email: { type: String, required: true, unique: true },
     introduction: { type: String },
     introduction: { type: String },
     password: String,
     password: String,
     apiToken: String,
     apiToken: String,
     lang: {
     lang: {
       type: String,
       type: String,
-      enum: Object.keys(getLanguageLabels()).map((k) => eval(k)),
-      default: LANG_EN_US
+      // eslint-disable-next-line no-eval
+      enum: Object.keys(getLanguageLabels()).map((k) => { return eval(k) }),
+      default: LANG_EN_US,
+    },
+    status: {
+      type: Number, required: true, default: STATUS_ACTIVE, index: true,
     },
     },
-    status: { type: Number, required: true, default: STATUS_ACTIVE, index: true  },
     createdAt: { type: Date, default: Date.now },
     createdAt: { type: Date, default: Date.now },
     lastLoginAt: { type: Date },
     lastLoginAt: { type: Date },
-    admin: { type: Boolean, default: 0, index: true  }
+    admin: { type: Boolean, default: 0, index: true },
   });
   });
   userSchema.plugin(mongoosePaginate);
   userSchema.plugin(mongoosePaginate);
   userSchema.plugin(uniqueValidator);
   userSchema.plugin(uniqueValidator);
@@ -73,8 +78,10 @@ module.exports = function(crowi) {
   function decideUserStatusOnRegistration() {
   function decideUserStatusOnRegistration() {
     validateCrowi();
     validateCrowi();
 
 
-    var Config = crowi.model('Config'),
-      config = crowi.getConfig();
+    const Config = crowi.model('Config');
+
+
+    const config = crowi.getConfig();
 
 
     if (!config.crowi) {
     if (!config.crowi) {
       return STATUS_ACTIVE; // is this ok?
       return STATUS_ACTIVE; // is this ok?
@@ -98,13 +105,13 @@ module.exports = function(crowi) {
   }
   }
 
 
   function generateRandomTempPassword() {
   function generateRandomTempPassword() {
-    var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!=-_';
-    var password = '';
-    var len = 12;
+    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!=-_';
+    let password = '';
+    const len = 12;
 
 
-    for (var i = 0; i < len; i++) {
-      var randomPoz = Math.floor(Math.random() * chars.length);
-      password += chars.substring(randomPoz, randomPoz+1);
+    for (let i = 0; i < len; i++) {
+      const randomPoz = Math.floor(Math.random() * chars.length);
+      password += chars.substring(randomPoz, randomPoz + 1);
     }
     }
 
 
     return password;
     return password;
@@ -113,30 +120,31 @@ module.exports = function(crowi) {
   function generatePassword(password) {
   function generatePassword(password) {
     validateCrowi();
     validateCrowi();
 
 
-    var hasher = crypto.createHash('sha256');
+    const hasher = crypto.createHash('sha256');
     hasher.update(crowi.env.PASSWORD_SEED + password);
     hasher.update(crowi.env.PASSWORD_SEED + password);
 
 
     return hasher.digest('hex');
     return hasher.digest('hex');
   }
   }
 
 
   function generateApiToken(user) {
   function generateApiToken(user) {
-    var hasher = crypto.createHash('sha256');
-    hasher.update((new Date).getTime() + user._id);
+    const hasher = crypto.createHash('sha256');
+    hasher.update((new Date()).getTime() + user._id);
 
 
     return hasher.digest('base64');
     return hasher.digest('base64');
   }
   }
 
 
   function getLanguageLabels() {
   function getLanguageLabels() {
-    var lang = {};
-    lang.LANG_EN    = LANG_EN;
+    const lang = {};
+    lang.LANG_EN = LANG_EN;
     lang.LANG_EN_US = LANG_EN_US;
     lang.LANG_EN_US = LANG_EN_US;
     lang.LANG_EN_GB = LANG_EN_GB;
     lang.LANG_EN_GB = LANG_EN_GB;
-    lang.LANG_JA    = LANG_JA;
+    lang.LANG_JA = LANG_JA;
 
 
     return lang;
     return lang;
   }
   }
 
 
   userSchema.methods.populateImage = async function() {
   userSchema.methods.populateImage = async function() {
+    // eslint-disable-next-line no-return-await
     return await this.populate(IMAGE_POPULATION);
     return await this.populate(IMAGE_POPULATION);
   };
   };
 
 
@@ -148,7 +156,7 @@ module.exports = function(crowi) {
   };
   };
 
 
   userSchema.methods.isPasswordValid = function(password) {
   userSchema.methods.isPasswordValid = function(password) {
-    return this.password == generatePassword(password);
+    return this.password === generatePassword(password);
   };
   };
 
 
   userSchema.methods.setPassword = function(password) {
   userSchema.methods.setPassword = function(password) {
@@ -165,47 +173,45 @@ module.exports = function(crowi) {
 
 
   userSchema.methods.updateLastLoginAt = function(lastLoginAt, callback) {
   userSchema.methods.updateLastLoginAt = function(lastLoginAt, callback) {
     this.lastLoginAt = lastLoginAt;
     this.lastLoginAt = lastLoginAt;
-    this.save(function(err, userData) {
+    this.save((err, userData) => {
       return callback(err, userData);
       return callback(err, userData);
     });
     });
   };
   };
 
 
   userSchema.methods.updateIsGravatarEnabled = function(isGravatarEnabled, callback) {
   userSchema.methods.updateIsGravatarEnabled = function(isGravatarEnabled, callback) {
     this.isGravatarEnabled = isGravatarEnabled;
     this.isGravatarEnabled = isGravatarEnabled;
-    this.save(function(err, userData) {
+    this.save((err, userData) => {
       return callback(err, userData);
       return callback(err, userData);
     });
     });
   };
   };
 
 
   userSchema.methods.updateIsEmailPublished = function(isEmailPublished, callback) {
   userSchema.methods.updateIsEmailPublished = function(isEmailPublished, callback) {
     this.isEmailPublished = isEmailPublished;
     this.isEmailPublished = isEmailPublished;
-    this.save(function(err, userData) {
+    this.save((err, userData) => {
       return callback(err, userData);
       return callback(err, userData);
     });
     });
   };
   };
 
 
   userSchema.methods.updatePassword = function(password, callback) {
   userSchema.methods.updatePassword = function(password, callback) {
     this.setPassword(password);
     this.setPassword(password);
-    this.save(function(err, userData) {
+    this.save((err, userData) => {
       return callback(err, userData);
       return callback(err, userData);
     });
     });
   };
   };
 
 
   userSchema.methods.updateApiToken = function(callback) {
   userSchema.methods.updateApiToken = function(callback) {
-    var self = this;
+    const self = this;
 
 
     self.apiToken = generateApiToken(this);
     self.apiToken = generateApiToken(this);
-    return new Promise(function(resolve, reject) {
-      self.save(function(err, userData) {
+    return new Promise(((resolve, reject) => {
+      self.save((err, userData) => {
         if (err) {
         if (err) {
           return reject(err);
           return reject(err);
         }
         }
-        else {
-          return resolve(userData);
-        }
-      });
 
 
-    });
+        return resolve(userData);
+      });
+    }));
   };
   };
 
 
   userSchema.methods.updateImage = async function(attachment) {
   userSchema.methods.updateImage = async function(attachment) {
@@ -230,7 +236,7 @@ module.exports = function(crowi) {
 
 
   userSchema.methods.updateGoogleId = function(googleId, callback) {
   userSchema.methods.updateGoogleId = function(googleId, callback) {
     this.googleId = googleId;
     this.googleId = googleId;
-    this.save(function(err, userData) {
+    this.save((err, userData) => {
       return callback(err, userData);
       return callback(err, userData);
     });
     });
   };
   };
@@ -245,7 +251,7 @@ module.exports = function(crowi) {
     this.username = username;
     this.username = username;
     this.status = STATUS_ACTIVE;
     this.status = STATUS_ACTIVE;
 
 
-    this.save(function(err, userData) {
+    this.save((err, userData) => {
       userEvent.emit('activated', userData);
       userEvent.emit('activated', userData);
       if (err) {
       if (err) {
         throw new Error(err);
         throw new Error(err);
@@ -257,7 +263,7 @@ module.exports = function(crowi) {
   userSchema.methods.removeFromAdmin = function(callback) {
   userSchema.methods.removeFromAdmin = function(callback) {
     debug('Remove from admin', this);
     debug('Remove from admin', this);
     this.admin = 0;
     this.admin = 0;
-    this.save(function(err, userData) {
+    this.save((err, userData) => {
       return callback(err, userData);
       return callback(err, userData);
     });
     });
   };
   };
@@ -265,7 +271,7 @@ module.exports = function(crowi) {
   userSchema.methods.makeAdmin = function(callback) {
   userSchema.methods.makeAdmin = function(callback) {
     debug('Admin', this);
     debug('Admin', this);
     this.admin = 1;
     this.admin = 1;
-    this.save(function(err, userData) {
+    this.save((err, userData) => {
       return callback(err, userData);
       return callback(err, userData);
     });
     });
   };
   };
@@ -278,7 +284,7 @@ module.exports = function(crowi) {
   userSchema.methods.statusActivate = function(callback) {
   userSchema.methods.statusActivate = function(callback) {
     debug('Activate User', this);
     debug('Activate User', this);
     this.status = STATUS_ACTIVE;
     this.status = STATUS_ACTIVE;
-    this.save(function(err, userData) {
+    this.save((err, userData) => {
       userEvent.emit('activated', userData);
       userEvent.emit('activated', userData);
       return callback(err, userData);
       return callback(err, userData);
     });
     });
@@ -291,12 +297,12 @@ module.exports = function(crowi) {
       this.email = '-';
       this.email = '-';
     }
     }
     if (this.name === undefined || this.name === null) { // migrate old data
     if (this.name === undefined || this.name === null) { // migrate old data
-      this.name = '-' + Date.now();
+      this.name = `-${Date.now()}`;
     }
     }
     if (this.username === undefined || this.usename === null) { // migrate old data
     if (this.username === undefined || this.usename === null) { // migrate old data
       this.username = '-';
       this.username = '-';
     }
     }
-    this.save(function(err, userData) {
+    this.save((err, userData) => {
       return callback(err, userData);
       return callback(err, userData);
     });
     });
   };
   };
@@ -315,21 +321,21 @@ module.exports = function(crowi) {
     this.googleId = null;
     this.googleId = null;
     this.isGravatarEnabled = false;
     this.isGravatarEnabled = false;
     this.image = null;
     this.image = null;
-    this.save(function(err, userData) {
+    this.save((err, userData) => {
       return callback(err, userData);
       return callback(err, userData);
     });
     });
   };
   };
 
 
   userSchema.methods.updateGoogleId = function(googleId, callback) {
   userSchema.methods.updateGoogleId = function(googleId, callback) {
     this.googleId = googleId;
     this.googleId = googleId;
-    this.save(function(err, userData) {
+    this.save((err, userData) => {
       return callback(err, userData);
       return callback(err, userData);
     });
     });
   };
   };
 
 
   userSchema.statics.getLanguageLabels = getLanguageLabels;
   userSchema.statics.getLanguageLabels = getLanguageLabels;
   userSchema.statics.getUserStatusLabels = function() {
   userSchema.statics.getUserStatusLabels = function() {
-    var userStatus = {};
+    const userStatus = {};
     userStatus[STATUS_REGISTERED] = '承認待ち';
     userStatus[STATUS_REGISTERED] = '承認待ち';
     userStatus[STATUS_ACTIVE] = 'Active';
     userStatus[STATUS_ACTIVE] = 'Active';
     userStatus[STATUS_SUSPENDED] = 'Suspended';
     userStatus[STATUS_SUSPENDED] = 'Suspended';
@@ -342,12 +348,12 @@ module.exports = function(crowi) {
   userSchema.statics.isEmailValid = function(email, callback) {
   userSchema.statics.isEmailValid = function(email, callback) {
     validateCrowi();
     validateCrowi();
 
 
-    var config = crowi.getConfig()
-      , whitelist = config.crowi['security:registrationWhiteList'];
+    const config = crowi.getConfig();
+    const whitelist = config.crowi['security:registrationWhiteList'];
 
 
     if (Array.isArray(whitelist) && whitelist.length > 0) {
     if (Array.isArray(whitelist) && whitelist.length > 0) {
-      return config.crowi['security:registrationWhiteList'].some(function(allowedEmail) {
-        var re = new RegExp(allowedEmail + '$');
+      return config.crowi['security:registrationWhiteList'].some((allowedEmail) => {
+        const re = new RegExp(`${allowedEmail}$`);
         return re.test(email);
         return re.test(email);
       });
       });
     }
     }
@@ -361,10 +367,10 @@ module.exports = function(crowi) {
       return user;
       return user;
     }
     }
 
 
-    var filteredUser = {};
-    var fields = USER_PUBLIC_FIELDS.split(' ');
-    for (var i = 0; i < fields.length; i++) {
-      var key = fields[i];
+    const filteredUser = {};
+    const fields = USER_PUBLIC_FIELDS.split(' ');
+    for (let i = 0; i < fields.length; i++) {
+      const key = fields[i];
       if (user[key]) {
       if (user[key]) {
         filteredUser[key] = user[key];
         filteredUser[key] = user[key];
       }
       }
@@ -374,22 +380,22 @@ module.exports = function(crowi) {
   };
   };
 
 
   userSchema.statics.findUsers = function(options, callback) {
   userSchema.statics.findUsers = function(options, callback) {
-    var sort = options.sort || {status: 1, createdAt: 1};
+    const sort = options.sort || { status: 1, createdAt: 1 };
 
 
     this.find()
     this.find()
       .sort(sort)
       .sort(sort)
       .skip(options.skip || 0)
       .skip(options.skip || 0)
       .limit(options.limit || 21)
       .limit(options.limit || 21)
-      .exec(function(err, userData) {
+      .exec((err, userData) => {
         callback(err, userData);
         callback(err, userData);
       });
       });
-
   };
   };
 
 
   userSchema.statics.findAllUsers = function(option) {
   userSchema.statics.findAllUsers = function(option) {
+    // eslint-disable-next-line no-param-reassign
     option = option || {};
     option = option || {};
 
 
-    const sort = option.sort || {createdAt: -1};
+    const sort = option.sort || { createdAt: -1 };
     const fields = option.fields || USER_PUBLIC_FIELDS;
     const fields = option.fields || USER_PUBLIC_FIELDS;
 
 
     let status = option.status || [STATUS_ACTIVE, STATUS_SUSPENDED];
     let status = option.status || [STATUS_ACTIVE, STATUS_SUSPENDED];
@@ -398,37 +404,37 @@ module.exports = function(crowi) {
     }
     }
 
 
     return this.find()
     return this.find()
-      .or(status.map(s => { return {status: s} }))
+      .or(status.map((s) => { return { status: s } }))
       .select(fields)
       .select(fields)
       .sort(sort);
       .sort(sort);
   };
   };
 
 
   userSchema.statics.findUsersByIds = function(ids, option) {
   userSchema.statics.findUsersByIds = function(ids, option) {
+    // eslint-disable-next-line no-param-reassign
     option = option || {};
     option = option || {};
 
 
-    const sort = option.sort || {createdAt: -1}
-      , status = option.status || STATUS_ACTIVE
-      , fields = option.fields || USER_PUBLIC_FIELDS
-      ;
+    const sort = option.sort || { createdAt: -1 };
+    const status = option.status || STATUS_ACTIVE;
+    const fields = option.fields || USER_PUBLIC_FIELDS;
 
 
-    return this.find({ _id: { $in: ids }, status: status })
+    return this.find({ _id: { $in: ids }, status })
       .select(fields)
       .select(fields)
       .sort(sort);
       .sort(sort);
   };
   };
 
 
   userSchema.statics.findAdmins = function(callback) {
   userSchema.statics.findAdmins = function(callback) {
-    var User = this;
-    this.find({admin: true})
-      .exec(function(err, admins) {
+    this.find({ admin: true })
+      .exec((err, admins) => {
         debug('Admins: ', admins);
         debug('Admins: ', admins);
         callback(err, admins);
         callback(err, admins);
       });
       });
   };
   };
 
 
   userSchema.statics.findUsersWithPagination = async function(options) {
   userSchema.statics.findUsersWithPagination = async function(options) {
-    var sort = options.sort || {status: 1, username: 1, createdAt: 1};
+    const sort = options.sort || { status: 1, username: 1, createdAt: 1 };
 
 
-    return await this.paginate({status: { $ne: STATUS_DELETED }}, { page: options.page || 1, limit: options.limit || PAGE_ITEMS }, function(err, result) {
+    // eslint-disable-next-line no-return-await
+    return await this.paginate({ status: { $ne: STATUS_DELETED } }, { page: options.page || 1, limit: options.limit || PAGE_ITEMS }, (err, result) => {
       if (err) {
       if (err) {
         debug('Error on pagination:', err);
         debug('Error on pagination:', err);
         throw new Error(err);
         throw new Error(err);
@@ -440,14 +446,14 @@ module.exports = function(crowi) {
 
 
   userSchema.statics.findUsersByPartOfEmail = function(emailPart, options) {
   userSchema.statics.findUsersByPartOfEmail = function(emailPart, options) {
     const status = options.status || null;
     const status = options.status || null;
-    const emailPartRegExp = new RegExp(emailPart.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'));
+    const emailPartRegExp = new RegExp(emailPart.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'));
     const User = this;
     const User = this;
 
 
     return new Promise((resolve, reject) => {
     return new Promise((resolve, reject) => {
       const query = User.find({ email: emailPartRegExp }, USER_PUBLIC_FIELDS);
       const query = User.find({ email: emailPartRegExp }, USER_PUBLIC_FIELDS);
 
 
       if (status) {
       if (status) {
-        query.and({status});
+        query.and({ status });
       }
       }
 
 
       query
       query
@@ -467,21 +473,21 @@ module.exports = function(crowi) {
     if (username == null) {
     if (username == null) {
       return Promise.resolve(null);
       return Promise.resolve(null);
     }
     }
-    return this.findOne({username});
+    return this.findOne({ username });
   };
   };
 
 
   userSchema.statics.findUserByApiToken = function(apiToken) {
   userSchema.statics.findUserByApiToken = function(apiToken) {
     if (apiToken == null) {
     if (apiToken == null) {
       return Promise.resolve(null);
       return Promise.resolve(null);
     }
     }
-    return this.findOne({apiToken});
+    return this.findOne({ apiToken });
   };
   };
 
 
   userSchema.statics.findUserByGoogleId = function(googleId, callback) {
   userSchema.statics.findUserByGoogleId = function(googleId, callback) {
     if (googleId == null) {
     if (googleId == null) {
       callback(null, null);
       callback(null, null);
     }
     }
-    this.findOne({googleId}, function(err, userData) {
+    this.findOne({ googleId }, (err, userData) => {
       callback(err, userData);
       callback(err, userData);
     });
     });
   };
   };
@@ -489,8 +495,8 @@ module.exports = function(crowi) {
   userSchema.statics.findUserByUsernameOrEmail = function(usernameOrEmail, password, callback) {
   userSchema.statics.findUserByUsernameOrEmail = function(usernameOrEmail, password, callback) {
     this.findOne()
     this.findOne()
       .or([
       .or([
-        {username: usernameOrEmail},
-        {email: usernameOrEmail},
+        { username: usernameOrEmail },
+        { email: usernameOrEmail },
       ])
       ])
       .exec((err, userData) => {
       .exec((err, userData) => {
         callback(err, userData);
         callback(err, userData);
@@ -498,8 +504,8 @@ module.exports = function(crowi) {
   };
   };
 
 
   userSchema.statics.findUserByEmailAndPassword = function(email, password, callback) {
   userSchema.statics.findUserByEmailAndPassword = function(email, password, callback) {
-    var hashedPassword = generatePassword(password);
-    this.findOne({email: email, password: hashedPassword}, function(err, userData) {
+    const hashedPassword = generatePassword(password);
+    this.findOne({ email, password: hashedPassword }, (err, userData) => {
       callback(err, userData);
       callback(err, userData);
     });
     });
   };
   };
@@ -521,17 +527,16 @@ module.exports = function(crowi) {
 
 
   userSchema.statics.countListByStatus = async function(status) {
   userSchema.statics.countListByStatus = async function(status) {
     const User = this;
     const User = this;
-    const conditions = {status: status};
+    const conditions = { status };
 
 
     // TODO count は非推奨。mongoose のバージョンアップ後に countDocuments に変更する。
     // TODO count は非推奨。mongoose のバージョンアップ後に countDocuments に変更する。
     return User.count(conditions);
     return User.count(conditions);
   };
   };
 
 
   userSchema.statics.isRegisterableUsername = async function(username) {
   userSchema.statics.isRegisterableUsername = async function(username) {
-    var User = this;
-    var usernameUsable = true;
+    let usernameUsable = true;
 
 
-    const userData = await this.findOne({username: username});
+    const userData = await this.findOne({ username });
     if (userData) {
     if (userData) {
       usernameUsable = false;
       usernameUsable = false;
     }
     }
@@ -539,24 +544,24 @@ module.exports = function(crowi) {
   };
   };
 
 
   userSchema.statics.isRegisterable = function(email, username, callback) {
   userSchema.statics.isRegisterable = function(email, username, callback) {
-    var User = this;
-    var emailUsable = true;
-    var usernameUsable = true;
+    const User = this;
+    let emailUsable = true;
+    let usernameUsable = true;
 
 
     // username check
     // username check
-    this.findOne({username: username}, function(err, userData) {
+    this.findOne({ username }, (err, userData) => {
       if (userData) {
       if (userData) {
         usernameUsable = false;
         usernameUsable = false;
       }
       }
 
 
       // email check
       // email check
-      User.findOne({email: email}, function(err, userData) {
+      User.findOne({ email }, (err, userData) => {
         if (userData) {
         if (userData) {
           emailUsable = false;
           emailUsable = false;
         }
         }
 
 
         if (!emailUsable || !usernameUsable) {
         if (!emailUsable || !usernameUsable) {
-          return callback(false, {email: emailUsable, username: usernameUsable});
+          return callback(false, { email: emailUsable, username: usernameUsable });
         }
         }
 
 
         return callback(true, {});
         return callback(true, {});
@@ -565,8 +570,8 @@ module.exports = function(crowi) {
   };
   };
 
 
   userSchema.statics.removeCompletelyById = function(id, callback) {
   userSchema.statics.removeCompletelyById = function(id, callback) {
-    var User = this;
-    User.findById(id, function(err, userData) {
+    const User = this;
+    User.findById(id, (err, userData) => {
       if (!userData) {
       if (!userData) {
         return callback(err, null);
         return callback(err, null);
       }
       }
@@ -578,7 +583,7 @@ module.exports = function(crowi) {
         return callback(new Error('Cannot remove completely the user whoes status is not INVITED'), null);
         return callback(new Error('Cannot remove completely the user whoes status is not INVITED'), null);
       }
       }
 
 
-      userData.remove(function(err) {
+      userData.remove((err) => {
         if (err) {
         if (err) {
           return callback(err, null);
           return callback(err, null);
         }
         }
@@ -589,58 +594,59 @@ module.exports = function(crowi) {
   };
   };
 
 
   userSchema.statics.resetPasswordByRandomString = function(id) {
   userSchema.statics.resetPasswordByRandomString = function(id) {
-    var User = this;
+    const User = this;
 
 
-    return new Promise(function(resolve, reject) {
-      User.findById(id, function(err, userData) {
+    return new Promise(((resolve, reject) => {
+      User.findById(id, (err, userData) => {
         if (!userData) {
         if (!userData) {
           return reject(new Error('User not found'));
           return reject(new Error('User not found'));
         }
         }
 
 
         // is updatable check
         // is updatable check
         // if (userData.isUp
         // if (userData.isUp
-        var newPassword = generateRandomTempPassword();
+        const newPassword = generateRandomTempPassword();
         userData.setPassword(newPassword);
         userData.setPassword(newPassword);
-        userData.save(function(err, userData) {
+        userData.save((err, userData) => {
           if (err) {
           if (err) {
             return reject(err);
             return reject(err);
           }
           }
 
 
-          resolve({user: userData, newPassword: newPassword});
+          resolve({ user: userData, newPassword });
         });
         });
       });
       });
-    });
+    }));
   };
   };
 
 
   userSchema.statics.createUsersByInvitation = function(emailList, toSendEmail, callback) {
   userSchema.statics.createUsersByInvitation = function(emailList, toSendEmail, callback) {
     validateCrowi();
     validateCrowi();
 
 
-    var User = this
-      , createdUserList = []
-      , Config = crowi.model('Config')
-      , config = crowi.getConfig()
-      , mailer = crowi.getMailer()
-      ;
+    const User = this;
+    const createdUserList = [];
+    const Config = crowi.model('Config');
+    const config = crowi.getConfig();
 
 
+    const mailer = crowi.getMailer();
     if (!Array.isArray(emailList)) {
     if (!Array.isArray(emailList)) {
       debug('emailList is not array');
       debug('emailList is not array');
     }
     }
 
 
     async.each(
     async.each(
       emailList,
       emailList,
-      function(email, next) {
-        var newUser = new User()
-          , tmpUsername, password;
+      (email, next) => {
+        const newUser = new User();
+        let tmpUsername;
+        let password;
 
 
+        // eslint-disable-next-line no-param-reassign
         email = email.trim();
         email = email.trim();
 
 
         // email check
         // email check
         // TODO: 削除済みはチェック対象から外そう〜
         // TODO: 削除済みはチェック対象から外そう〜
-        User.findOne({email: email}, function(err, userData) {
+        User.findOne({ email }, (err, userData) => {
           // The user is exists
           // The user is exists
           if (userData) {
           if (userData) {
             createdUserList.push({
             createdUserList.push({
-              email: email,
+              email,
               password: null,
               password: null,
               user: null,
               user: null,
             });
             });
@@ -648,8 +654,10 @@ module.exports = function(crowi) {
             return next();
             return next();
           }
           }
 
 
-          tmpUsername = 'temp_' + Math.random().toString(36).slice(-16);
+          /* eslint-disable newline-per-chained-call */
+          tmpUsername = `temp_${Math.random().toString(36).slice(-16)}`;
           password = Math.random().toString(36).slice(-16);
           password = Math.random().toString(36).slice(-16);
+          /* eslint-enable newline-per-chained-call */
 
 
           newUser.username = tmpUsername;
           newUser.username = tmpUsername;
           newUser.email = email;
           newUser.email = email;
@@ -662,10 +670,10 @@ module.exports = function(crowi) {
             newUser.lang = globalLang;
             newUser.lang = globalLang;
           }
           }
 
 
-          newUser.save(function(err, userData) {
+          newUser.save((err, userData) => {
             if (err) {
             if (err) {
               createdUserList.push({
               createdUserList.push({
-                email: email,
+                email,
                 password: null,
                 password: null,
                 user: null,
                 user: null,
               });
               });
@@ -673,8 +681,8 @@ module.exports = function(crowi) {
             }
             }
             else {
             else {
               createdUserList.push({
               createdUserList.push({
-                email: email,
-                password: password,
+                email,
+                password,
                 user: userData,
                 user: userData,
               });
               });
               debug('saved!', email);
               debug('saved!', email);
@@ -684,7 +692,7 @@ module.exports = function(crowi) {
           });
           });
         });
         });
       },
       },
-      function(err) {
+      (err) => {
         if (err) {
         if (err) {
           debug('error occured while iterate email list');
           debug('error occured while iterate email list');
         }
         }
@@ -693,43 +701,42 @@ module.exports = function(crowi) {
           // TODO: メール送信部分のロジックをサービス化する
           // TODO: メール送信部分のロジックをサービス化する
           async.each(
           async.each(
             createdUserList,
             createdUserList,
-            function(user, next) {
+            (user, next) => {
               if (user.password === null) {
               if (user.password === null) {
                 return next();
                 return next();
               }
               }
 
 
               mailer.send({
               mailer.send({
                 to: user.email,
                 to: user.email,
-                subject: 'Invitation to ' + Config.appTitle(config),
+                subject: `Invitation to ${Config.appTitle(config)}`,
                 template: path.join(crowi.localeDir, 'en-US/admin/userInvitation.txt'),
                 template: path.join(crowi.localeDir, 'en-US/admin/userInvitation.txt'),
                 vars: {
                 vars: {
                   email: user.email,
                   email: user.email,
                   password: user.password,
                   password: user.password,
                   url: crowi.configManager.getSiteUrl(),
                   url: crowi.configManager.getSiteUrl(),
                   appTitle: Config.appTitle(config),
                   appTitle: Config.appTitle(config),
-                }
+                },
               },
               },
-              function(err, s) {
+              (err, s) => {
                 debug('completed to send email: ', err, s);
                 debug('completed to send email: ', err, s);
                 next();
                 next();
-              }
-              );
+              });
             },
             },
-            function(err) {
+            (err) => {
               debug('Sending invitation email completed.', err);
               debug('Sending invitation email completed.', err);
-            }
+            },
           );
           );
         }
         }
 
 
         debug('createdUserList!!! ', createdUserList);
         debug('createdUserList!!! ', createdUserList);
         return callback(null, createdUserList);
         return callback(null, createdUserList);
-      }
+      },
     );
     );
   };
   };
 
 
   userSchema.statics.createUserByEmailAndPasswordAndStatus = async function(name, username, email, password, lang, status, callback) {
   userSchema.statics.createUserByEmailAndPasswordAndStatus = async function(name, username, email, password, lang, status, callback) {
-    const User = this
-      , newUser = new User();
+    const User = this;
+    const newUser = new User();
 
 
     // check user upper limit
     // check user upper limit
     const isUserCountExceedsUpperLimit = await User.isUserCountExceedsUpperLimit();
     const isUserCountExceedsUpperLimit = await User.isUserCountExceedsUpperLimit();
@@ -741,6 +748,7 @@ module.exports = function(crowi) {
     // check email duplication because email must be unique
     // check email duplication because email must be unique
     const count = await this.count({ email });
     const count = await this.count({ email });
     if (count > 0) {
     if (count > 0) {
+      // eslint-disable-next-line no-param-reassign
       email = generateRandomEmail();
       email = generateRandomEmail();
     }
     }
 
 
@@ -764,13 +772,13 @@ module.exports = function(crowi) {
     newUser.createdAt = Date.now();
     newUser.createdAt = Date.now();
     newUser.status = status || decideUserStatusOnRegistration();
     newUser.status = status || decideUserStatusOnRegistration();
 
 
-    newUser.save(function(err, userData) {
+    newUser.save((err, userData) => {
       if (err) {
       if (err) {
         logger.error('createUserByEmailAndPasswordAndStatus failed: ', err);
         logger.error('createUserByEmailAndPasswordAndStatus failed: ', err);
         return callback(err);
         return callback(err);
       }
       }
 
 
-      if (userData.status == STATUS_ACTIVE) {
+      if (userData.status === STATUS_ACTIVE) {
         userEvent.emit('activated', userData);
         userEvent.emit('activated', userData);
       }
       }
       return callback(err, userData);
       return callback(err, userData);
@@ -804,9 +812,10 @@ module.exports = function(crowi) {
   };
   };
 
 
   userSchema.statics.getUsernameByPath = function(path) {
   userSchema.statics.getUsernameByPath = function(path) {
-    var username = null;
-    if (m = path.match(/^\/user\/([^\/]+)\/?/)) {
-      username = m[1];
+    let username = null;
+    const match = path.match(/^\/user\/([^/]+)\/?/);
+    if (match) {
+      username = match[1];
     }
     }
 
 
     return username;
     return username;
@@ -818,19 +827,19 @@ module.exports = function(crowi) {
     }
     }
   }
   }
 
 
-  userSchema.statics.STATUS_REGISTERED  = STATUS_REGISTERED;
-  userSchema.statics.STATUS_ACTIVE      = STATUS_ACTIVE;
-  userSchema.statics.STATUS_SUSPENDED   = STATUS_SUSPENDED;
-  userSchema.statics.STATUS_DELETED     = STATUS_DELETED;
-  userSchema.statics.STATUS_INVITED     = STATUS_INVITED;
+  userSchema.statics.STATUS_REGISTERED = STATUS_REGISTERED;
+  userSchema.statics.STATUS_ACTIVE = STATUS_ACTIVE;
+  userSchema.statics.STATUS_SUSPENDED = STATUS_SUSPENDED;
+  userSchema.statics.STATUS_DELETED = STATUS_DELETED;
+  userSchema.statics.STATUS_INVITED = STATUS_INVITED;
   userSchema.statics.USER_PUBLIC_FIELDS = USER_PUBLIC_FIELDS;
   userSchema.statics.USER_PUBLIC_FIELDS = USER_PUBLIC_FIELDS;
-  userSchema.statics.IMAGE_POPULATION   = IMAGE_POPULATION;
-  userSchema.statics.PAGE_ITEMS         = PAGE_ITEMS;
+  userSchema.statics.IMAGE_POPULATION = IMAGE_POPULATION;
+  userSchema.statics.PAGE_ITEMS = PAGE_ITEMS;
 
 
-  userSchema.statics.LANG_EN            = LANG_EN;
-  userSchema.statics.LANG_EN_US         = LANG_EN_US;
-  userSchema.statics.LANG_EN_GB         = LANG_EN_US;
-  userSchema.statics.LANG_JA            = LANG_JA;
+  userSchema.statics.LANG_EN = LANG_EN;
+  userSchema.statics.LANG_EN_US = LANG_EN_US;
+  userSchema.statics.LANG_EN_GB = LANG_EN_US;
+  userSchema.statics.LANG_JA = LANG_JA;
 
 
   return mongoose.model('User', userSchema);
   return mongoose.model('User', userSchema);
 };
 };