Browse Source

Merge pull request #2414 from weseek/support/refactor-register

Support/refactor register
Yuki Takei 5 years ago
parent
commit
28d20be53e

+ 2 - 6
src/server/models/user.js

@@ -425,12 +425,8 @@ module.exports = function(crowi) {
       .sort(sort);
       .sort(sort);
   };
   };
 
 
-  userSchema.statics.findAdmins = function(callback) {
-    this.find({ admin: true })
-      .exec((err, admins) => {
-        debug('Admins: ', admins);
-        callback(err, admins);
-      });
+  userSchema.statics.findAdmins = async function() {
+    return this.find({ admin: true });
   };
   };
 
 
   userSchema.statics.findUsersByPartOfEmail = function(emailPart, options) {
   userSchema.statics.findUsersByPartOfEmail = function(emailPart, options) {

+ 1 - 4
src/server/routes/apiv3/statistics.js

@@ -8,8 +8,6 @@ const router = express.Router();
 
 
 const helmet = require('helmet');
 const helmet = require('helmet');
 
 
-const util = require('util');
-
 const USER_STATUS_MASTER = {
 const USER_STATUS_MASTER = {
   1: 'registered',
   1: 'registered',
   2: 'active',
   2: 'active',
@@ -54,8 +52,7 @@ module.exports = (crowi) => {
     const inactiveUserTotal = userCountResults.invited + userCountResults.deleted + userCountResults.suspended + userCountResults.registered;
     const inactiveUserTotal = userCountResults.invited + userCountResults.deleted + userCountResults.suspended + userCountResults.registered;
 
 
     // Get admin users
     // Get admin users
-    const findAdmins = util.promisify(User.findAdmins).bind(User);
-    const adminUsers = await findAdmins();
+    const adminUsers = await User.findAdmins();
 
 
     return {
     return {
       total: activeUserCount + inactiveUserTotal,
       total: activeUserCount + inactiveUserTotal,

+ 30 - 32
src/server/routes/login.js

@@ -120,7 +120,7 @@ module.exports = function(crowi, app) {
           return res.redirect('/register');
           return res.redirect('/register');
         }
         }
 
 
-        User.createUserByEmailAndPassword(name, username, email, password, undefined, (err, userData) => {
+        User.createUserByEmailAndPassword(name, username, email, password, undefined, async(err, userData) => {
           if (err) {
           if (err) {
             if (err.name === 'UserUpperLimitException') {
             if (err.name === 'UserUpperLimitException') {
               req.flash('registerWarningMessage', 'Can not register more than the maximum number of users.');
               req.flash('registerWarningMessage', 'Can not register more than the maximum number of users.');
@@ -131,39 +131,11 @@ module.exports = function(crowi, app) {
             return res.redirect('/register');
             return res.redirect('/register');
           }
           }
 
 
-
-          // 作成後、承認が必要なモードなら、管理者に通知する
-          const appTitle = appService.getAppTitle();
-          if (configManager.getConfig('crowi', 'security:registrationMode') === aclService.labels.SECURITY_REGISTRATION_MODE_RESTRICTED) {
-            // TODO send mail
-            User.findAdmins((err, admins) => {
-              async.each(
-                admins,
-                (adminUser, next) => {
-                  mailer.send({
-                    to: adminUser.email,
-                    subject: `[${appTitle}:admin] A New User Created and Waiting for Activation`,
-                    template: path.join(crowi.localeDir, 'en-US/admin/userWaitingActivation.txt'),
-                    vars: {
-                      createdUser: userData,
-                      adminUser,
-                      url: appService.getSiteUrl(),
-                      appTitle,
-                    },
-                  },
-                  (err, s) => {
-                    debug('completed to send email: ', err, s);
-                    next();
-                  });
-                },
-                (err) => {
-                  debug('Sending invitation email completed.', err);
-                },
-              );
-            });
+          if (configManager.getConfig('crowi', 'security:registrationMode') !== aclService.labels.SECURITY_REGISTRATION_MODE_RESTRICTED) {
+            // send mail asynchronous
+            sendEmailToAllAdmins(userData);
           }
           }
 
 
-
           // 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.
@@ -180,6 +152,32 @@ module.exports = function(crowi, app) {
     }
     }
   };
   };
 
 
+  async function sendEmailToAllAdmins(userData) {
+    // send mails to all admin users (derived from crowi) -- 2020.06.18 Yuki Takei
+    const admins = await User.findAdmins();
+
+    const appTitle = appService.getAppTitle();
+
+    const promises = admins.map((admin) => {
+      return mailer.send({
+        to: admin.email,
+        subject: `[${appTitle}:admin] A New User Created and Waiting for Activation`,
+        template: path.join(crowi.localeDir, 'en-US/admin/userWaitingActivation.txt'),
+        vars: {
+          createdUser: userData,
+          admin,
+          url: appService.getSiteUrl(),
+          appTitle,
+        },
+      });
+    })
+
+    const results = await Promise.allSettled(promises);
+    results
+      .filter(result => result.status === 'rejected')
+      .forEach(result => logger.error(result.reason));
+  }
+
   actions.invited = async function(req, res) {
   actions.invited = async function(req, res) {
     if (!req.user) {
     if (!req.user) {
       return res.redirect('/login');
       return res.redirect('/login');

+ 11 - 17
src/server/util/mailer.js

@@ -93,25 +93,19 @@ module.exports = function(crowi) {
     return mc;
     return mc;
   }
   }
 
 
-  function send(config, callback = () => {}) {
-    if (mailer) {
-      const templateVars = config.vars || {};
-      return swig.renderFile(
-        config.template,
-        templateVars,
-        (err, output) => {
-          if (err) {
-            throw err;
-          }
-
-          config.text = output;
-          return mailer.sendMail(setupMailConfig(config), callback);
-        },
-      );
+  async function send(config) {
+    if (mailer == null) {
+      throw new Error('Mailer is not completed to set up. Please set up SMTP or AWS setting.');
     }
     }
 
 
-    logger.debug('Mailer is not completed to set up. Please set up SMTP or AWS setting.');
-    return callback(new Error('Mailer is not completed to set up. Please set up SMTP or AWS setting.'), null);
+    const templateVars = config.vars || {};
+    const output = await swig.renderFile(
+      config.template,
+      templateVars,
+    );
+
+    config.text = output;
+    return mailer.sendMail(setupMailConfig(config));
   }
   }