Просмотр исходного кода

Add backend validation for new ingredients

Lee Morgan 6 лет назад
Родитель
Сommit
68ddcdfda0

+ 8 - 0
controllers/ingredientData.js

@@ -1,5 +1,6 @@
 const Merchant = require("../models/merchant");
 const Ingredient = require("../models/ingredient");
+const Validator = require("./validator.js");
 
 module.exports = {
     //GET - gets a list of all database ingredients
@@ -34,6 +35,13 @@ module.exports = {
             return res.redirect("/");
         }
 
+        if(!Validator.ingredient(req.body.ingredient)){
+            return res.json("Error:  ingredient contains illegal characters");
+        }
+        if(!Validator.quantity(req.body.quantity)){
+            return res.json("Error: inappropriate quantity");
+        }
+
         let ingredientPromise = Ingredient.create((req.body.ingredient));
         let merchantPromise = Merchant.findOne({_id: req.session.user});
         let newIngredient;

+ 35 - 0
controllers/validator.js

@@ -0,0 +1,35 @@
+module.exports = {
+    ingredient: function(ingredient){
+        if(!this.isSanitary([ingredient.name, ingredient.category, ingredient.unit])){
+            return false;
+        }
+
+        return true;
+    },
+
+    quantity: function(num){
+        if(isNaN(num) || num === ""){
+            return false;
+        }
+
+        if(num < 0){
+            return false;
+        }
+
+        return true;
+    },
+
+    isSanitary: function(strings){
+        let disallowed = ["\\", "<", ">", "$", "{", "}", "(", ")"];
+
+        for(let i = 0; i < strings.length; i++){
+            for(let j = 0; j < disallowed.length; j++){
+                if(strings[i].includes(disallowed[j])){
+                    return false;
+                }
+            }
+        }
+
+        return true;
+    }
+}

+ 3 - 2
views/dashboardPage/components/components.js

@@ -330,7 +330,7 @@ let newIngredientComp = {
         let loader = document.getElementById("loaderContainer");
         loader.style.display = "flex";
 
-        if(validator.ingredient(newIngredient)){
+        // if(validator.ingredient(newIngredient)){
             fetch("/ingredients/create", {
                 method: "POST",
                 headers: {
@@ -358,9 +358,10 @@ let newIngredientComp = {
                     }
                 })
                 .catch((err)=>{
+                    console.log(err);
                     banner.createError("Something went wrong.  Try refreshing the page");
                 });
-        }
+        // }
     }
 }