Parcourir la source

Merge pull request #1196 from weseek/create-user-data

Create user data
itizawa il y a 6 ans
Parent
commit
3352164db2
2 fichiers modifiés avec 98 ajouts et 112 suppressions
  1. 94 108
      src/server/models/user.js
  2. 4 4
      src/server/routes/admin.js

+ 94 - 108
src/server/models/user.js

@@ -2,14 +2,12 @@
 
 const debug = require('debug')('growi:models:user');
 const logger = require('@alias/logger')('growi:models:user');
-const path = require('path');
 const mongoose = require('mongoose');
 const uniqueValidator = require('mongoose-unique-validator');
 const mongoosePaginate = require('mongoose-paginate');
 
 const ObjectId = mongoose.Schema.Types.ObjectId;
 const crypto = require('crypto');
-const async = require('async');
 
 module.exports = function(crowi) {
   const STATUS_REGISTERED = 1;
@@ -612,125 +610,113 @@ module.exports = function(crowi) {
     return newPassword;
   };
 
-  userSchema.statics.createUsersByInvitation = function(emailList, toSendEmail, callback) {
-    validateCrowi();
-
+  userSchema.statics.createUserByEmail = async function(email) {
     const configManager = crowi.configManager;
 
     const User = this;
-    const createdUserList = [];
-    const mailer = crowi.getMailer();
+    const newUser = new User();
 
-    if (!Array.isArray(emailList)) {
-      debug('emailList is not array');
-    }
+    /* eslint-disable newline-per-chained-call */
+    const tmpUsername = `temp_${Math.random().toString(36).slice(-16)}`;
+    const password = Math.random().toString(36).slice(-16);
+    /* eslint-enable newline-per-chained-call */
 
-    async.each(
-      emailList,
-      (email, next) => {
-        const newUser = new User();
-        let tmpUsername;
-        let password;
-
-        // eslint-disable-next-line no-param-reassign
-        email = email.trim();
-
-        // email check
-        // TODO: 削除済みはチェック対象から外そう〜
-        User.findOne({ email }, (err, userData) => {
-          // The user is exists
-          if (userData) {
-            createdUserList.push({
-              email,
-              password: null,
-              user: null,
-            });
-
-            return next();
-          }
+    newUser.username = tmpUsername;
+    newUser.email = email;
+    newUser.setPassword(password);
+    newUser.createdAt = Date.now();
+    newUser.status = STATUS_INVITED;
 
-          /* eslint-disable newline-per-chained-call */
-          tmpUsername = `temp_${Math.random().toString(36).slice(-16)}`;
-          password = Math.random().toString(36).slice(-16);
-          /* eslint-enable newline-per-chained-call */
+    const globalLang = configManager.getConfig('crowi', 'app:globalLang');
+    if (globalLang != null) {
+      newUser.lang = globalLang;
+    }
 
-          newUser.username = tmpUsername;
-          newUser.email = email;
-          newUser.setPassword(password);
-          newUser.createdAt = Date.now();
-          newUser.status = STATUS_INVITED;
+    try {
+      const newUserData = await newUser.save();
+      return {
+        email,
+        password,
+        user: newUserData,
+      };
+    }
+    catch (err) {
+      return {
+        email,
+      };
+    }
+  };
 
-          const globalLang = configManager.getConfig('crowi', 'app:globalLang');
-          if (globalLang != null) {
-            newUser.lang = globalLang;
-          }
+  userSchema.statics.createUsersByEmailList = async function(emailList) {
+    const User = this;
 
-          newUser.save((err, userData) => {
-            if (err) {
-              createdUserList.push({
-                email,
-                password: null,
-                user: null,
-              });
-              debug('save failed!! ', err);
-            }
-            else {
-              createdUserList.push({
-                email,
-                password,
-                user: userData,
-              });
-              debug('saved!', email);
-            }
-
-            next();
-          });
-        });
-      },
-      (err) => {
-        if (err) {
-          debug('error occured while iterate email list');
-        }
+    // check exists and get list of tyr to create
+    const existingUserList = await User.find({ email: { $in: emailList }, userStatus: { $ne: STATUS_DELETED } });
+    const existingEmailList = existingUserList.map((user) => { return user.email });
+    const creationEmailList = emailList.filter((email) => { return existingEmailList.indexOf(email) === -1 });
 
-        if (toSendEmail) {
-          // TODO: メール送信部分のロジックをサービス化する
-          async.each(
-            createdUserList,
-            (user, next) => {
-              if (user.password === null) {
-                return next();
-              }
-
-              const appTitle = crowi.appService.getAppTitle();
-
-              mailer.send({
-                to: user.email,
-                subject: `Invitation to ${appTitle}`,
-                template: path.join(crowi.localeDir, 'en-US/admin/userInvitation.txt'),
-                vars: {
-                  email: user.email,
-                  password: user.password,
-                  url: crowi.appService.getSiteUrl(),
-                  appTitle,
-                },
-              },
-              (err, s) => {
-                debug('completed to send email: ', err, s);
-                next();
-              });
-            },
-            (err) => {
-              debug('Sending invitation email completed.', err);
-            },
-          );
-        }
+    const createdUserList = [];
+    await Promise.all(creationEmailList.map(async(email) => {
+      const createdEmail = await this.createUserByEmail(email);
+      createdUserList.push(createdEmail);
+    }));
 
-        debug('createdUserList!!! ', createdUserList);
-        return callback(null, createdUserList);
-      },
-    );
+    return [existingEmailList, createdUserList];
   };
 
+  userSchema.statics.createUsersByInvitation = async function(emailList, toSendEmail) {
+    validateCrowi();
+
+    // TODO GW-206 move to anothor function
+    // const mailer = crowi.getMailer();
+
+    if (!Array.isArray(emailList)) {
+      debug('emailList is not array');
+    }
+
+    // TODO GW-230 use List in client side
+    // const afterWorkEmailList = await this.createUsersByEmailList(emailList);
+
+  };
+
+  //  TODO GW-206 Independence as function
+  // if (toSendEmail) {
+  //   // TODO: メール送信部分のロジックをサービス化する
+  //   async.each(
+  //     createdUserList,
+  //     (user, next) => {
+  //       if (user.password === null) {
+  //         return next();
+  //       }
+
+  //       const appTitle = crowi.appService.getAppTitle();
+
+  //       mailer.send({
+  //         to: user.email,
+  //         subject: `Invitation to ${appTitle}`,
+  //         template: path.join(crowi.localeDir, 'en-US/admin/userInvitation.txt'),
+  //         vars: {
+  //           email: user.email,
+  //           password: user.password,
+  //           url: crowi.appService.getSiteUrl(),
+  //           appTitle,
+  //         },
+  //       },
+  //       (err, s) => {
+  //         debug('completed to send email: ', err, s);
+  //         next();
+  //       });
+  //     },
+  //     (err) => {
+  //       debug('Sending invitation email completed.', err);
+  //     },
+  //   );
+  // }
+
+  //     debug('createdUserList!!! ', createdUserList);
+  //   },
+  // );
+
   userSchema.statics.createUserByEmailAndPasswordAndStatus = async function(name, username, email, password, lang, status, callback) {
     const User = this;
     const newUser = new User();

+ 4 - 4
src/server/routes/admin.js

@@ -454,12 +454,12 @@ module.exports = function(crowi, app) {
       return res.json(ApiResponse.error('Valid email address is required'));
     }
 
-    // const array = req.body.emailInputValue.split('\n');
-    // const emailList = array.filter((element) => { return element.match(/.+@.+\..+/) });
+    const array = req.body.emailInputValue.split('\n');
+    const emailList = array.filter((element) => { return element.match(/.+@.+\..+/) });
+    const shapedEmailList = emailList.map((email) => { return email.trim() });
 
     try {
-      // TODO GW-170 Create users based on mail list passed in array
-      // await User.createUsersByInvitation(req.body.emailList.split('\n'), req.body.sendEmail);
+      await User.createUsersByInvitation(shapedEmailList, req.body.sendEmail);
       return res.json(ApiResponse.success());
     }
     catch (err) {