Преглед изворни кода

Merge pull request #851 from weseek/imprv/refactor-installer

refactor installer
Yuki Takei пре 7 година
родитељ
комит
be5ef7f3f8

+ 1 - 1
src/client/js/components/InstallerForm.jsx

@@ -43,7 +43,7 @@ class InstallerForm extends React.Component {
           <small>{ this.props.t('installer.initial_account_will_be_administrator_automatically') }</small>
         </p>
 
-        <form role="form" action="/installer/createAdmin" method="post" id="register-form">
+        <form role="form" action="/installer" method="post" id="register-form">
           <div className="input-group m-t-20 m-b-20 mx-auto">
             <div className="radio radio-primary radio-inline">
               <input type="radio" id="radioLangEn" name="registerForm[app:globalLang]" value="en-US"

+ 5 - 0
src/server/models/user.js

@@ -270,6 +270,11 @@ module.exports = function(crowi) {
     });
   };
 
+  userSchema.methods.asyncMakeAdmin = async function(callback) {
+    this.admin = 1;
+    return this.save();
+  };
+
   userSchema.methods.statusActivate = function(callback) {
     debug('Activate User', this);
     this.status = STATUS_ACTIVE;

+ 2 - 2
src/server/routes/index.js

@@ -32,8 +32,8 @@ module.exports = function(crowi, app) {
 
   app.get('/'                        , middleware.applicationInstalled(), loginRequired(crowi, app, false) , page.showTopPage);
 
-  app.get('/installer'               , middleware.applicationNotInstalled() , middleware.checkSearchIndicesGenerated(crowi, app) , installer.index);
-  app.post('/installer/createAdmin'  , middleware.applicationNotInstalled() , form.register , csrf, installer.createAdmin);
+  app.get('/installer'               , middleware.applicationNotInstalled() , installer.index);
+  app.post('/installer'              , middleware.applicationNotInstalled() , form.register , csrf, installer.install);
   //app.post('/installer/user'         , middleware.applicationNotInstalled() , installer.createFirstUser);
 
   app.get('/login/error/:reason'     , login.error);

+ 55 - 33
src/server/routes/installer.js

@@ -11,28 +11,50 @@ module.exports = function(crowi, app) {
 
   const actions = {};
 
-  function createInitialPages(owner, lang) {
+  async function initSearchIndex() {
+    const search = crowi.getSearcher();
+    if (search == null) {
+      return;
+    }
+
+    await search.deleteIndex();
+    await search.buildIndex();
+    await search.addAllPages();
+  }
+
+  async function createInitialPages(owner, lang) {
+    const promises = [];
+
     // create portal page for '/'
     const welcomeMarkdownPath = path.join(crowi.localeDir, lang, 'welcome.md');
     const welcomeMarkdown = fs.readFileSync(welcomeMarkdownPath);
-    Page.create('/', welcomeMarkdown, owner, {});
+    promises.push(Page.create('/', welcomeMarkdown, owner, {}));
 
     // create /Sandbox
     const sandboxMarkdownPath = path.join(crowi.localeDir, lang, 'sandbox.md');
     const sandboxMarkdown = fs.readFileSync(sandboxMarkdownPath);
-    Page.create('/Sandbox', sandboxMarkdown, owner, {});
+    promises.push(Page.create('/Sandbox', sandboxMarkdown, owner, {}));
 
     // create /Sandbox/Bootstrap3
     const bs3MarkdownPath = path.join(crowi.localeDir, 'en-US', 'sandbox-bootstrap3.md');
     const bs3Markdown = fs.readFileSync(bs3MarkdownPath);
-    Page.create('/Sandbox/Bootstrap3', bs3Markdown, owner, {});
+    promises.push(Page.create('/Sandbox/Bootstrap3', bs3Markdown, owner, {}));
+
+    await Promise.all(promises);
+
+    try {
+      await initSearchIndex();
+    }
+    catch (err) {
+      logger.error('Failed to build Elasticsearch Indices', err);
+    }
   }
 
   actions.index = function(req, res) {
     return res.render('installer');
   };
 
-  actions.createAdmin = function(req, res, next) {
+  actions.install = async function(req, res, next) {
     const registerForm = req.body.registerForm || {};
 
     if (!req.form.isValid) {
@@ -45,39 +67,39 @@ module.exports = function(crowi, app) {
     const password = registerForm.password;
     const language = registerForm['app:globalLang'] || 'en-US';
 
-    User.createUserByEmailAndPassword(name, username, email, password, language, function(err, userData) {
+    let adminUser;
+    try {
+      adminUser = await User.createUser(name, username, email, password, language);
+      await adminUser.asyncMakeAdmin();
+    }
+    catch (err) {
+      req.form.errors.push('管理ユーザーの作成に失敗しました。' + err.message);
+      return res.render('installer');
+    }
+
+    Config.applicationInstall(function(err, configs) {
       if (err) {
-        req.form.errors.push('管理ユーザーの作成に失敗しました。' + err.message);
-        // TODO
-        return res.render('installer');
+        logger.error(err);
+        return;
       }
 
-      userData.makeAdmin(function(err, userData) {
-        Config.applicationInstall(function(err, configs) {
-          if (err) {
-            logger.error(err);
-            return;
-          }
-
-          // save the globalLang config, and update the config cache
-          Config.updateNamespaceByArray('crowi', {'app:globalLang': language}, function(err, config) {
-            Config.updateConfigCache('crowi', config);
-          });
-
-          // login with passport
-          req.logIn(userData, (err) => {
-            if (err) { return next() }
-            else {
-              req.flash('successMessage', 'GROWI のインストールが完了しました!はじめに、このページで各種設定を確認してください。');
-              return res.redirect('/admin/app');
-            }
-          });
-        });
-
-        // create initial pages
-        createInitialPages(userData, language);
+      // save the globalLang config, and update the config cache
+      Config.updateNamespaceByArray('crowi', {'app:globalLang': language}, function(err, config) {
+        Config.updateConfigCache('crowi', config);
+      });
+
+      // login with passport
+      req.logIn(adminUser, (err) => {
+        if (err) { return next() }
+        else {
+          req.flash('successMessage', 'GROWI のインストールが完了しました!はじめに、このページで各種設定を確認してください。');
+          return res.redirect('/admin/app');
+        }
       });
     });
+
+    // create initial pages
+    await createInitialPages(adminUser, language);
   };
 
   return actions;

+ 1 - 28
src/server/util/middlewares.js

@@ -284,7 +284,7 @@ exports.accessTokenParser = function(crowi, app) {
 // this is for Installer
 exports.applicationNotInstalled = function() {
   return function(req, res, next) {
-    var config = req.config;
+    const config = req.config;
 
     if (Object.keys(config.crowi).length !== 0) {
       req.flash('errorMessage', 'Application already installed.');
@@ -295,33 +295,6 @@ exports.applicationNotInstalled = function() {
   };
 };
 
-exports.checkSearchIndicesGenerated = function(crowi, app) {
-  return function(req, res, next) {
-    const searcher = crowi.getSearcher();
-
-    // build index
-    if (searcher) {
-      searcher.buildIndex()
-        .then((data) => {
-          if (!data.errors) {
-            debug('Index created.');
-          }
-          return searcher.addAllPages();
-        })
-        .catch((error) => {
-          if (error.message != null && error.message.match(/index_already_exists_exception/)) {
-            debug('Creating index is failed: ', error.message);
-          }
-          else {
-            console.log(`Error while building index of Elasticsearch': ${error.message}`);
-          }
-        });
-    }
-
-    return next();
-  };
-};
-
 exports.applicationInstalled = function() {
   return function(req, res, next) {
     var config = req.config;