Jelajahi Sumber

extract common method to reject unexpected config keys

Naoki427 8 bulan lalu
induk
melakukan
9170b429c9
1 mengubah file dengan 24 tambahan dan 16 penghapusan
  1. 24 16
      apps/app/src/server/routes/admin.js

+ 24 - 16
apps/app/src/server/routes/admin.js

@@ -89,6 +89,28 @@ module.exports = function(crowi, app) {
 
   actions.api = {};
 
+  /**
+   * Reject request if unexpected keys are present in form.
+   * Logs the keys and returns error response.
+   *
+   * @param {Object} form
+   * @param {Array<string>} allowedKeys
+   * @param {Object} res
+   * @returns {boolean}
+   */
+  function rejectUnexpectedKeys(form, allowedKeys, res) {
+    const receivedKeys = Object.keys(form);
+    const unexpectedKeys = receivedKeys.filter(key => !allowedKeys.includes(key));
+
+    if (unexpectedKeys.length > 0) {
+      logger.warn('Unexpected keys were found in request body.', { unexpectedKeys });
+      res.json(ApiResponse.error('Invalid config keys provided.'));
+      return false;
+    }
+
+    return true;
+  }
+
   /**
    * save esa settings, update config cache, and response json
    *
@@ -105,14 +127,7 @@ module.exports = function(crowi, app) {
     }
 
     const ALLOWED_KEYS = ['importer:esa:team_name', 'importer:esa:access_token'];
-    const receivedKeys = Object.keys(form);
-
-    const unexpectedKeys = receivedKeys.filter(key => !ALLOWED_KEYS.includes(key));
-
-    if (unexpectedKeys.length > 0) {
-      logger.warn('Esa config update contained unexpected keys.', { unexpectedKeys });
-      return res.json(ApiResponse.error('Invalid config keys provided.'));
-    }
+    if (!rejectUnexpectedKeys(form, ALLOWED_KEYS, res)) return;
 
     await configManager.updateConfigs(form);
     importer.initializeEsaClient(); // let it run in the back aftert res
@@ -137,14 +152,7 @@ module.exports = function(crowi, app) {
     }
 
     const ALLOWED_KEYS = ['importer:qiita:team_name', 'importer:qiita:access_token'];
-    const receivedKeys = Object.keys(form);
-
-    const unexpectedKeys = receivedKeys.filter(key => !ALLOWED_KEYS.includes(key));
-
-    if (unexpectedKeys.length > 0) {
-      logger.warn('Qiita config update contained unexpected keys.', { unexpectedKeys });
-      return res.json(ApiResponse.error('Invalid config keys provided.'));
-    }
+    if (!rejectUnexpectedKeys(form, ALLOWED_KEYS, res)) return;
 
     await configManager.updateConfigs(form);
     importer.initializeQiitaClient(); // let it run in the back aftert res