Procházet zdrojové kódy

Update middleware to check merchant against owner.
Update middleware to pass forward bot the merchant and the owner.
Returned res.locals.merchant to its previous state.

Lee Morgan před 5 roky
rodič
revize
fa2a0eecb0

+ 1 - 1
controllers/emailVerification.js

@@ -20,7 +20,7 @@ module.exports = {
                 mailgun.messages().send(mailgunData, (err, body)=>{});
 
 
-                return res.render(`verifyPage/verify`, {id: owner._id, email: owner.email, banner: res.locals.owner});
+                return res.render(`verifyPage/verify`, {id: owner._id, email: owner.email, banner: res.locals.merchant});
             })
             .catch((err)=>{
                 req.session.error = "ERROR: UNABLE TO SEND VERIFICATION EMAIL";

+ 15 - 15
controllers/ingredientData.js

@@ -39,9 +39,9 @@ module.exports = {
 
                 newIngredient.quantity = helper.convertQuantityToBaseUnit(req.body.quantity, req.body.defaultUnit);
 
-                res.locals.owner.inventory.push(newIngredient);
+                res.locals.merchant.inventory.push(newIngredient);
 
-                return res.locals.owner.save();
+                return res.locals.merchant.save();
             })
             .then((response)=>{
                 return res.json(newIngredient);
@@ -77,19 +77,19 @@ module.exports = {
             })
             .then((ingredient)=>{
                 let updatedIngredient = {};
-                for(let i = 0; i < res.locals.owner.inventory.length; i++){
-                    if(res.locals.owner.inventory[i].ingredient.toString() === req.body.id){
-                        res.locals.owner.inventory[i].defaultUnit = req.body.unit;
+                for(let i = 0; i < res.locals.merchant.inventory.length; i++){
+                    if(res.locals.merchant.inventory[i].ingredient.toString() === req.body.id){
+                        res.locals.merchant.inventory[i].defaultUnit = req.body.unit;
 
-                        if(res.locals.owner.inventory[i].quantity !== req.body.quantity){
+                        if(res.locals.merchant.inventory[i].quantity !== req.body.quantity){
                             new InventoryAdjustment({
                                 date: new Date(),
                                 merchant: req.session.owner,
                                 ingredient: req.body.id,
-                                quantity: req.body.quantity - res.locals.owner.inventory[i].quantity
+                                quantity: req.body.quantity - res.locals.merchant.inventory[i].quantity
                             }).save().catch(()=>{});
 
-                            res.locals.owner.inventory[i].quantity = req.body.quantity;
+                            res.locals.merchant.inventory[i].quantity = req.body.quantity;
                         }
 
                         updatedIngredient = {
@@ -102,7 +102,7 @@ module.exports = {
                     }
                 }
 
-                res.locals.owner.save().catch((err)=>{throw err});
+                res.locals.merchant.save().catch((err)=>{throw err});
                 return res.json(updatedIngredient);
             })
             .catch((err)=>{
@@ -172,11 +172,11 @@ module.exports = {
         }
 
         for(let i = 0; i < merchantData.length; i++){
-            res.locals.owner.inventory.push(merchantData[i]);
+            res.locals.merchant.inventory.push(merchantData[i]);
         }
 
         //Update the database
-        Promise.all([Ingredient.create(ingredients), res.locals.owner.save()])
+        Promise.all([Ingredient.create(ingredients), res.locals.merchant.save()])
             .then((response)=>{
                 return res.json(merchantData);
             })
@@ -210,14 +210,14 @@ module.exports = {
 
     //DELETE - Removes an ingredient from the merchant's inventory
     removeIngredient: function(req, res){
-        for(let i = 0; i < res.locals.owner.inventory.length; i++){
-            if(req.params.id === res.locals.owner.inventory[i].ingredient._id.toString()){
-                res.locals.owner.inventory.splice(i, 1);
+        for(let i = 0; i < res.locals.merchant.inventory.length; i++){
+            if(req.params.id === res.locals.merchant.inventory[i].ingredient._id.toString()){
+                res.locals.merchant.inventory.splice(i, 1);
                 break;
             }
         }
 
-        Promise.all([res.locals.owner.save(), Ingredient.deleteOne({_id: req.params.id})])
+        Promise.all([res.locals.merchant.save(), Ingredient.deleteOne({_id: req.params.id})])
             .then((response)=>{
                 return res.json({});
             })

+ 13 - 13
controllers/merchantData.js

@@ -93,7 +93,7 @@ module.exports = {
     updateIngredientQuantities: function(req, res){
         let adjustments = [];
         let changedIngredients = [];
-        res.locals.owner
+        res.locals.merchant
             .populate("inventory.ingredient")
             .execPopulate()
             .then((merchant)=>{
@@ -189,28 +189,28 @@ module.exports = {
     response = Merchant
     */
     updateData: async function(req, res){
-        if(req.body.email !== res.locals.owner.email){
+        if(req.body.email !== res.locals.merchant.email){
             let merchantCheck = await Merchant.findOne({email: req.body.email});
             if(merchantCheck !== null){
                 return res.json("USER WITH THIS EMAIL ADDRESS ALREADY EXISTS");
             }
 
-            res.locals.owner.email = req.body.email;
-            res.locals.owner.status.push("unverified");
+            res.locals.merchant.email = req.body.email;
+            res.locals.merchant.status.push("unverified");
 
             const mailgunData = {
                 from: "The Subline <clientsupport@thesubline.net>",
-                to: res.locals.owner.email,
+                to: res.locals.merchant.email,
                 subject: "Email Verification",
                 html: verifyEmail({
-                    name: res.locals.owner.name,
-                    link: `${process.env.SITE}/verify/${res.locals.owner._id}/${res.locals.owner.sessionId}`
+                    name: res.locals.merchant.name,
+                    link: `${process.env.SITE}/verify/${res.locals.merchant._id}/${res.locals.merchant.sessionId}`
                 })
             };
             mailgun.messages().send(mailgunData, (err, body)=>{});
         }
 
-        res.locals.owner.save()
+        res.locals.merchant.save()
             .then((merchant)=>{
                 return res.json(merchant);
             })
@@ -236,19 +236,19 @@ module.exports = {
             return res.json("PASSWORDS DO NOT MATCH");
         }
 
-        bcrypt.compare(req.body.current, res.locals.owner.password, (err, result)=>{
+        bcrypt.compare(req.body.current, res.locals.merchant.password, (err, result)=>{
             if(result === true){
                 let salt = bcrypt.genSaltSync(10);
                 let hash = bcrypt.hashSync(req.body.new, salt);
 
-                res.locals.owner.password = hash;
+                res.locals.merchant.password = hash;
 
                 let newExpiration = new Date();
                 newExpiration.setDate(newExpiration.getDate() + 90);
-                res.locals.owner.session.sessionId = helper.generateId(25);
-                res.locals.owner.session.expiration = newExpiration;
+                res.locals.merchant.session.sessionId = helper.generateId(25);
+                res.locals.merchant.session.expiration = newExpiration;
 
-                res.locals.owner.save()
+                res.locals.merchant.save()
                     .then((merchant)=>{
                         req.session.error = "PLEASE LOG IN";
                         return res.json({redirect: `http://${process.env.SITE}/login`});

+ 13 - 13
controllers/orderData.js

@@ -41,7 +41,7 @@ module.exports = {
 
         Order.aggregate([
             {$match:{
-                merchant: new ObjectId(res.locals.owner._id),
+                merchant: new ObjectId(res.locals.merchant._id),
                 date: {
                     $gte: from,
                     $lt: to
@@ -72,7 +72,7 @@ module.exports = {
     */ 
     createOrder: function(req, res){
         let newOrder = new Order(req.body);
-        newOrder.merchant = res.locals.owner._id;
+        newOrder.merchant = res.locals.merchant._id;
         newOrder.save()
             .then((response)=>{
                 res.json(response);
@@ -89,14 +89,14 @@ module.exports = {
 
         
             for(let i = 0; i < req.body.ingredients.length; i++){
-                for(let j = 0; j < res.locals.owner.inventory.length; j++){
-                    if(req.body.ingredients[i].ingredient === res.locals.owner.inventory[j].ingredient.toString()){
-                        res.locals.owner.inventory[j].quantity += parseFloat(req.body.ingredients[i].quantity);
+                for(let j = 0; j < res.locals.merchant.inventory.length; j++){
+                    if(req.body.ingredients[i].ingredient === res.locals.merchant.inventory[j].ingredient.toString()){
+                        res.locals.merchant.inventory[j].quantity += parseFloat(req.body.ingredients[i].quantity);
                     }
                 }
             }
 
-            res.locals.owner.save().catch((err)=>{});
+            res.locals.merchant.save().catch((err)=>{});
     },
 
     createFromSpreadsheet: function(req, res){
@@ -149,14 +149,14 @@ module.exports = {
         }
 
         let merchant = {};
-        res.locals.owner
+        res.locals.merchant
             .populate("inventory.ingredient")
             .execPopulate()
             .then((response)=>{
                 merchant = response;
 
                 let order = new Order({
-                    merchant: res.locals.owner._id,
+                    merchant: res.locals.merchant._id,
                     name: array[1][locations.name],
                     date: spreadsheetDate,
                     taxes: parseInt(array[1][locations.taxes] * 100),
@@ -211,7 +211,7 @@ module.exports = {
     GET - Creates and sends a template xlsx for uploading orders
     */
     spreadsheetTemplate: function(req, res){
-        res.locals.owner
+        res.locals.merchant
             .populate("inventory.ingredient")
             .execPopulate()
             .then((merchant)=>{
@@ -251,15 +251,15 @@ module.exports = {
         Order.findOne({_id: req.params.id})
             .then((order)=>{
                 for(let i = 0; i < order.ingredients.length; i++){
-                    for(let j = 0; j < res.locals.owner.inventory.length; j++){
-                        if(order.ingredients[i].ingredient.toString() === res.locals.owner.inventory[j].ingredient.toString()){
-                            res.locals.owner.inventory[j].quantity -= order.ingredients[i].quantity;
+                    for(let j = 0; j < res.locals.merchant.inventory.length; j++){
+                        if(order.ingredients[i].ingredient.toString() === res.locals.merchant.inventory[j].ingredient.toString()){
+                            res.locals.merchant.inventory[j].quantity -= order.ingredients[i].quantity;
                             break;
                         }
                     }
                 }
 
-                return Promise.all([Order.deleteOne({_id: req.params.id}), res.locals.owner.save()]);
+                return Promise.all([Order.deleteOne({_id: req.params.id}), res.locals.merchant.save()]);
             })
             .then((response)=>{
                 res.json({});

+ 1 - 1
controllers/otherData.js

@@ -87,7 +87,7 @@ module.exports = {
     */
     feedback: function(req, res){
         let feedback = new Feedback({
-            merchant: res.locals.owner._id,
+            merchant: res.locals.merchant._id,
             title: req.body.title,
             content: req.body.content,
             date: new Date(req.body.date)

+ 14 - 14
controllers/recipeData.js

@@ -21,7 +21,7 @@ module.exports = {
     */
     createRecipe: function(req, res){
         let recipe = new Recipe({
-            merchant: res.locals.owner._id,
+            merchant: res.locals.merchant._id,
             name: req.body.name,
             price: Math.round(req.body.price * 100),
             ingredients: req.body.ingredients
@@ -29,8 +29,8 @@ module.exports = {
 
         recipe.save()
             .then((newRecipe)=>{
-                res.locals.owner.recipes.push(recipe);
-                res.locals.owner.save().catch((err)=>{throw err});
+                res.locals.merchant.recipes.push(recipe);
+                res.locals.merchant.save().catch((err)=>{throw err});
 
                 return res.json(newRecipe);
             })
@@ -61,7 +61,7 @@ module.exports = {
         Recipe.findOne({_id: req.body.id})
             .then((recipe)=>{
                 new ArchivedRecipe({
-                    merchant: res.locals.owner._id,
+                    merchant: res.locals.merchant._id,
                     name: recipe.name,
                     price: recipe.price,
                     date: new Date(),
@@ -90,13 +90,13 @@ module.exports = {
 
     //DELETE - removes a single recipe from the merchant and the database
     removeRecipe: function(req, res){
-        if(res.locals.owner.pos === "square"){
+        if(res.locals.merchant.pos === "square"){
             return res.json("YOU MUST EDIT YOUR RECIPES INSIDE SQUARE");
         }
         
-        for(let i = 0; i < res.locals.owner.recipes.length; i++){
-            if(res.locals.owner.recipes[i].toString() === req.params.id){
-                res.locals.owner.recipes.splice(i, 1);
+        for(let i = 0; i < res.locals.merchant.recipes.length; i++){
+            if(res.locals.merchant.recipes[i].toString() === req.params.id){
+                res.locals.merchant.recipes.splice(i, 1);
                 break;
             }
         }
@@ -139,7 +139,7 @@ module.exports = {
 
         let merchant = {};
         let ingredients = [];
-        res.locals.owner
+        res.locals.merchant
             .populate("inventory.ingredient")
             .execPopulate()
             .then((response)=>{
@@ -164,7 +164,7 @@ module.exports = {
 
                     if(array[i][locations.name] !== undefined){
                         currentRecipe = {
-                            merchant: res.locals.owner._id,
+                            merchant: res.locals.merchant._id,
                             name: array[i][locations.name],
                             price: parseInt(array[i][locations.price] * 100),
                             ingredients: []
@@ -228,18 +228,18 @@ module.exports = {
 
             let recipe = new Recipe({
                 posId: array[i][0],
-                merchant: res.locals.owner._id,
+                merchant: res.locals.merchant._id,
                 name: name,
                 price: parseInt(array[i][7] * 100) || 0,
                 ingredients: []
             });
 
             recipes.push(recipe);
-            res.locals.owner.recipes.push(recipe);
+            res.locals.merchant.recipes.push(recipe);
         }
 
 
-        Promise.all([Recipe.create(recipes), res.locals.owner.save()])
+        Promise.all([Recipe.create(recipes), res.locals.merchant.save()])
             .then((response)=>{
                 return res.json(response[0]);
             })
@@ -250,7 +250,7 @@ module.exports = {
     },
 
     spreadsheetTemplate: function(req, res){
-        res.locals.owner
+        res.locals.merchant
             .populate("inventory.ingredient")
             .execPopulate()
             .then((merchant)=>{

+ 10 - 10
controllers/renderer.js

@@ -29,12 +29,12 @@ module.exports = {
     Renders inventoryPage
     */
     displayDashboard: function(req, res){
-        if(res.locals.owner.status.includes("unverified")) {
+        if(res.locals.merchant.status.includes("unverified")) {
             req.session.error = "PLEASE VERIFY YOUR EMAIL ADDRESS";
-            return res.redirect(`/verify/email/${res.locals.owner._id}`);
+            return res.redirect(`/verify/email/${res.locals.merchant._id}`);
         }
 
-        res.locals.owner
+        res.locals.merchant
             .populate("inventory.ingredient")
             .populate("recipes")
             .execPopulate()
@@ -44,7 +44,7 @@ module.exports = {
 
                 return Transaction.aggregate([
                     {$match: {
-                        merchant: new ObjectId(res.locals.owner._id),
+                        merchant: new ObjectId(res.locals.merchant._id),
                         date: {$gte: firstDay},
                     }},
                     {$sort: {date: -1}},
@@ -58,7 +58,7 @@ module.exports = {
                 if(res.locals.pos !== "none"){
                     let latest = null;
                     if(transactions.length === 0){
-                        let latestTransaction = await Transaction.find({merchant: res.locals.owner._id}).sort({date: -1}).limit(1);
+                        let latestTransaction = await Transaction.find({merchant: res.locals.merchant._id}).sort({date: -1}).limit(1);
                         if(latestTransaction.length > 0) latest = new Date(latest[0].date);
                     }else{
                         latest = new Date(transactions[0].date);
@@ -69,7 +69,7 @@ module.exports = {
                         let now = new Date();
 
                         let postData = {
-                            location_ids: [res.locals.owner.square.location],
+                            location_ids: [res.locals.merchant.square.location],
                             query: {
                                 filter: {
                                     date_time_filter: {
@@ -91,7 +91,7 @@ module.exports = {
                         };
 
                         do{
-                            let newOrders = await helper.getSquareData(res.locals.owner, postData);
+                            let newOrders = await helper.getSquareData(res.locals.merchant, postData);
                             postData.cursor = newOrders.cursor;
                             for(let i = 0; i < newOrders.length; i++){
                                 for(let j = 0; j < newOrders[i].recipes.length; j++){
@@ -103,13 +103,13 @@ module.exports = {
                     }
                 }
 
-                res.locals.owner._id = undefined;
+                res.locals.merchant._id = undefined;
                 res.locals.password = undefined;
-                res.locals.owner.status = undefined;
+                res.locals.merchant.status = undefined;
                 res.locals.square = undefined;
                 res.locals.session = undefined;
 
-                return res.render("dashboardPage/dashboard", {merchant: res.locals.owner, transactions: transactions});
+                return res.render("dashboardPage/dashboard", {merchant: res.locals.merchant, transactions: transactions});
             })
             .catch((err)=>{
                 req.session.error = "ERROR: UNABLE TO RETRIEVE DATA";

+ 1 - 1
controllers/squareData.js

@@ -269,7 +269,7 @@ module.exports = {
         let merchantRecipes = [];
         let newRecipes = [];
     
-        res.locals.owner
+        res.locals.merchant
             .populate("recipes")
             .execPopulate()
             .then((fetchedMerchant)=>{

+ 16 - 16
controllers/transactionData.js

@@ -37,7 +37,7 @@ module.exports = {
 
         Transaction.aggregate([
             {$match: {
-                merchant: ObjectId(res.locals.owner._id),
+                merchant: ObjectId(res.locals.merchant._id),
                 date: {
                     $gte: from,
                     $lt: to
@@ -72,23 +72,23 @@ module.exports = {
         let keys = Object.keys(req.body.ingredientUpdates);
 
         for(let i = 0; i < keys.length; i++){
-            for(let j = 0; j < res.locals.owner.inventory.length; j++){
-                if(res.locals.owner.inventory[j].ingredient._id.toString() === keys[i]){
-                    res.locals.owner.inventory[j].quantity -= req.body.ingredientUpdates[keys[i]];
+            for(let j = 0; j < res.locals.merchant.inventory.length; j++){
+                if(res.locals.merchant.inventory[j].ingredient._id.toString() === keys[i]){
+                    res.locals.merchant.inventory[j].quantity -= req.body.ingredientUpdates[keys[i]];
 
                     break;
                 }
             }
         }
 
-        res.locals.owner.save()
+        res.locals.merchant.save()
             .then((merchant)=>{
                 if(req.body.date === null){
                     throw "NEW TRANSACTIONS MUST CONTAIN A DATE";
                 }
 
                 return new Transaction({
-                    merchant: res.locals.owner._id,
+                    merchant: res.locals.merchant._id,
                     date: new Date(req.body.date),
                     device: "none",
                     recipes: req.body.recipes
@@ -156,13 +156,13 @@ module.exports = {
             }
         }
 
-        res.locals.owner
+        res.locals.merchant
             .populate("recipes")
             .populate("inventory.ingredient")
             .execPopulate()
             .then((merchant)=>{
                 let transaction = new Transaction({
-                    merchant: res.locals.owner._id,
+                    merchant: res.locals.merchant._id,
                     date: spreadsheetDate,
                     recipes: []
                 });
@@ -230,7 +230,7 @@ module.exports = {
     },
 
     spreadsheetTemplate: function(req, res){
-        res.locals.owner
+        res.locals.merchant
             .populate("recipes")
             .execPopulate()
             .then((merchant)=>{
@@ -266,16 +266,16 @@ module.exports = {
                     const recipe = transaction.recipes[i].recipe;
                     for(let j = 0; j < recipe.ingredients.length; j++){
                         const ingredient = recipe.ingredients[j].ingredient;
-                        for(let k = 0; k < res.locals.owner.inventory.length; k++){
-                            if(ingredient.toString() === res.locals.owner.inventory[k].ingredient.toString()){
-                                res.locals.owner.inventory[k].quantity += recipe.ingredients[j].quantity * transaction.recipes[i].quantity;
+                        for(let k = 0; k < res.locals.merchant.inventory.length; k++){
+                            if(ingredient.toString() === res.locals.merchant.inventory[k].ingredient.toString()){
+                                res.locals.merchant.inventory[k].quantity += recipe.ingredients[j].quantity * transaction.recipes[i].quantity;
                                 break;
                             }
                         }
                     }
                 }
                 
-                return Promise.all([Transaction.deleteOne({_id: req.params.id}), res.locals.owner.save()]);
+                return Promise.all([Transaction.deleteOne({_id: req.params.id}), res.locals.merchant.save()]);
             })
             .then((response)=>{
                 res.json({});
@@ -305,7 +305,7 @@ module.exports = {
         let newTransactions = [];
         for(let i = 0; i < 5000; i++){
             let newTransaction = new Transaction({
-                merchant: res.locals.owner._id,
+                merchant: res.locals.merchant._id,
                 date: randomDate(),
                 recipes: []
             });
@@ -313,11 +313,11 @@ module.exports = {
             let numberOfRecipes = Math.floor((Math.random() * 5) + 1);
 
             for(let j = 0; j < numberOfRecipes; j++){
-                let recipeNumber = Math.floor(Math.random() * res.locals.owner.recipes.length);
+                let recipeNumber = Math.floor(Math.random() * res.locals.merchant.recipes.length);
                 let randQuantity = Math.floor((Math.random() * 3) + 1);
 
                 newTransaction.recipes.push({
-                    recipe: res.locals.owner.recipes[recipeNumber],
+                    recipe: res.locals.merchant.recipes[recipeNumber],
                     quantity: randQuantity
                 });
             }

+ 12 - 8
middleware.js

@@ -9,22 +9,26 @@ module.exports = {
             return res.redirect("/login");
         }
     
-        Owner.findOne({"session.sessionId": req.session.owner})
-            .then((owner)=>{
-                if(owner === null) throw "login";
+        let owner = Owner.findOne({"session.sessionId": req.session.owner});
+        let merchant = Merchant.findOne({_id: req.session.merchant});
+        Promise.all([owner, merchant])
+            .then((response)=>{
+                if(response[0] === null || response[1] === null) throw "login";
+                if(response[0]._id !== response[1].owner) throw "login";
     
                 //Check if session is out of date
-                if(owner.session.expiration < new Date()){
+                if(response[0].session.expiration < new Date()){
                     let newExpiration = new Date();
                     newExpiration.setDate(newExpiration.getDate() + 90);
     
-                    owner.session.sessionId = helper.generateId(25);
-                    owner.session.expiration = newExpiration;
-                    owner.save();
+                    response[0].session.sessionId = helper.generateId(25);
+                    response[0].session.expiration = newExpiration;
+                    response[0].save();
                     throw "login";
                 }
 
-                res.locals.owner = owner;
+                res.locals.owner = response[0];
+                res.locals.merchant = response[1];
                 return next();
             })
             .catch((err)=>{