From 3de86d5d60b1d1a1811f647ca24ebe5e6da8e12e Mon Sep 17 00:00:00 2001 From: prakharCrudcook Date: Sat, 3 Aug 2024 16:00:04 +0530 Subject: [PATCH 01/22] fix [index.js]: moved dotenv config before any initializations --- index.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 6a2384f..1057800 100644 --- a/index.js +++ b/index.js @@ -6,9 +6,10 @@ const dotenv = require("dotenv") const app = express() const Routes = require("./routes/route.js") +dotenv.config(); + const PORT = process.env.PORT || 5000 -dotenv.config(); app.use(express.json({ limit: '10mb' })) app.use(cors()) From cfc918ffbb7b0608d30cbb2f67a5f88a8f89355c Mon Sep 17 00:00:00 2001 From: prakharCrudcook Date: Sat, 3 Aug 2024 16:03:27 +0530 Subject: [PATCH 02/22] fix [models]: fixed various synatx and naming errors in models --- models/orderSchema.js | 2 +- models/productSchema.js | 4 ++-- models/sellerSchema.js | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/models/orderSchema.js b/models/orderSchema.js index bffca5b..7ce5dc6 100644 --- a/models/orderSchema.js +++ b/models/orderSchema.js @@ -117,4 +117,4 @@ const orderSchema = new mongoose.Schema( }, }); -module.exports = mongoose.model("customer", orderSchema); \ No newline at end of file +module.exports = mongoose.model("order", orderSchema); \ No newline at end of file diff --git a/models/productSchema.js b/models/productSchema.js index 8755a9a..7a8e25d 100644 --- a/models/productSchema.js +++ b/models/productSchema.js @@ -49,7 +49,7 @@ const productSchema = mongoose.Schema( }, date: { type: Date, - default: Text, + default: Date.now, }, }, ], @@ -59,4 +59,4 @@ const productSchema = mongoose.Schema( }, }, { timestamps: false}); -module.exports = mongoose.mongoose("product", productSchema) \ No newline at end of file +module.exports = mongoose.model("product", productSchema) \ No newline at end of file diff --git a/models/sellerSchema.js b/models/sellerSchema.js index 557a1ec..b09f981 100644 --- a/models/sellerSchema.js +++ b/models/sellerSchema.js @@ -25,4 +25,4 @@ const sellerSchema = new mongoose.Schema({ } }); -moduleexports = mongoose.model("seller", sellerSchema) \ No newline at end of file +module.exports = mongoose.model("seller", sellerSchema) \ No newline at end of file From 24ca1eeb530f762c42ccdbf6dc0f0a649807c36c Mon Sep 17 00:00:00 2001 From: prakharCrudcook Date: Sat, 3 Aug 2024 16:04:45 +0530 Subject: [PATCH 03/22] fix [routes]: exported the router for routes.js --- routes/route.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/routes/route.js b/routes/route.js index 7919542..21acc77 100644 --- a/routes/route.js +++ b/routes/route.js @@ -69,3 +69,5 @@ router.put('/CustomerUpdate/:id', cartUpdate); router.post('/newOrder', newOrder); router.get('/getOrderedProductsByCustomer/:id', getOrderedProductsBySeller); router.get('/getOrderedProductsBySeller/:id', getOrderedProductsBySeller); + +module.exports = router; From 0ce2642441b3897050649bb89144d7eb937c0236 Mon Sep 17 00:00:00 2001 From: prakharCrudcook Date: Sat, 3 Aug 2024 16:05:51 +0530 Subject: [PATCH 04/22] fix [routes]: fixed the wrong import for sellerLogin and sellerRegister --- routes/route.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/routes/route.js b/routes/route.js index 21acc77..5ec706e 100644 --- a/routes/route.js +++ b/routes/route.js @@ -4,7 +4,7 @@ const authMiddleware = require('../middleware/authMiddleware.js'); const { sellerRegister, sellerLogIn -} = require('../controllers/orderController.js'); +} = require('../controllers/sellerController.js'); const { productCreate, From 1f4186035f40bde1f78e5a465c8e203a41379394 Mon Sep 17 00:00:00 2001 From: prakharCrudcook Date: Sat, 3 Aug 2024 16:07:28 +0530 Subject: [PATCH 05/22] fix [utils]: fixed the way that token.js was getting SECRET_KEY --- utils/token.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils/token.js b/utils/token.js index 855ef6c..8575717 100644 --- a/utils/token.js +++ b/utils/token.js @@ -1,6 +1,6 @@ const jwt = require("jsonwebtoken"); const createNewToken = (payload) => { - return jwt.sign({ userId: payload }, process.getuid.SECRET_KEY, { expiresIn: '10d' }); + return jwt.sign({ userId: payload }, process.env.SECRET_KEY, { expiresIn: '10d' }); } From fe6cd7091ddc3464e866e058f35a79f302234e4e Mon Sep 17 00:00:00 2001 From: prakharCrudcook Date: Sat, 3 Aug 2024 16:12:47 +0530 Subject: [PATCH 06/22] fix [sellerController]: added role to token for easy authorization and fixed syntax errors --- controllers/sellerController.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/controllers/sellerController.js b/controllers/sellerController.js index b9943bb..271fac4 100644 --- a/controllers/sellerController.js +++ b/controllers/sellerController.js @@ -9,7 +9,7 @@ const sellerRegister = async (req, res) => { const seller = new Seller({ ...req.body, - password: bcrypt.hash + password: hashedPass }); const existingSellerByEmail = await Seller.findOne({ email: req.body.email }); @@ -25,11 +25,11 @@ const sellerRegister = async (req, res) => { let result = await seller.save(); result.password = undefined; - const token = createNewToken(result._id) + const token = createNewToken({ userId: result._id, userRole: result.role }) result = { ...result._doc, - token: token + token }; res.send(result); @@ -47,11 +47,11 @@ const sellerLogIn = async (req, res) => { if (validated) { seller.password = undefined; - const token = createNewToken(seller._id) + const token = createNewToken({ userId: seller._id, userRole: seller.role }) seller = { ...seller._doc, - token: tokens + token }; res.send(seller); From 9ec1342e725db5d58015f81bea15d31139d3fc05 Mon Sep 17 00:00:00 2001 From: prakharCrudcook Date: Sat, 3 Aug 2024 16:13:36 +0530 Subject: [PATCH 07/22] fix [sellerController]: fixed the way createNewToken function was imported --- controllers/sellerController.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controllers/sellerController.js b/controllers/sellerController.js index 271fac4..c056ff0 100644 --- a/controllers/sellerController.js +++ b/controllers/sellerController.js @@ -1,6 +1,6 @@ const bcrypt = require('bcrypt'); const Seller = require('../models/sellerSchema.js'); -const { createNewToken } = require('../utils/token.js'); +const createNewToken = require('../utils/token.js'); const sellerRegister = async (req, res) => { try { From f4dddedba2be1441cb7d411519a2bc33d9d6ecd4 Mon Sep 17 00:00:00 2001 From: prakharCrudcook Date: Sat, 3 Aug 2024 16:15:30 +0530 Subject: [PATCH 08/22] fix [customerController]: fixed the way createNewToken was imported --- controllers/customerController.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controllers/customerController.js b/controllers/customerController.js index 09911c6..71b18e6 100644 --- a/controllers/customerController.js +++ b/controllers/customerController.js @@ -1,6 +1,6 @@ const bcrypt = require('bcrypt'); const Customer = require('../models/customerSchema.js'); -const { createNewToken } = require('../utils/token.js'); +const createNewToken = require('../utils/token.js'); const customerRegister = async (req, res) => { try { From b6a1bfada6663f07a0ddf99a433e5e3c71058d71 Mon Sep 17 00:00:00 2001 From: prakharCrudcook Date: Sat, 3 Aug 2024 16:18:11 +0530 Subject: [PATCH 09/22] enhance [sellerController]: shifted from promise based save to mongoose create --- controllers/sellerController.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controllers/sellerController.js b/controllers/sellerController.js index c056ff0..801d52c 100644 --- a/controllers/sellerController.js +++ b/controllers/sellerController.js @@ -22,7 +22,7 @@ const sellerRegister = async (req, res) => { res.send({ message: 'Shop name already exists' }); } else { - let result = await seller.save(); + let result = await Seller.create(seller); result.password = undefined; const token = createNewToken({ userId: result._id, userRole: result.role }) From 44e6501fee436040dc53c0d9f0f59ad510a2cd1b Mon Sep 17 00:00:00 2001 From: prakharCrudcook Date: Sat, 3 Aug 2024 16:19:13 +0530 Subject: [PATCH 10/22] enhance [customerController]: shifted from promise based save to mongoose create --- controllers/customerController.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controllers/customerController.js b/controllers/customerController.js index 71b18e6..a7cacc7 100644 --- a/controllers/customerController.js +++ b/controllers/customerController.js @@ -18,7 +18,7 @@ const customerRegister = async (req, res) => { res.send({ message: 'Email already exists' }); } else { - let result = await customer.save(); + let result = await Customer.create(customer); result.password = undefined; const token = createNewToken(result._id) From 445a62b012a3a4ce12e1ce1a566925e1baebd4ca Mon Sep 17 00:00:00 2001 From: prakharCrudcook Date: Sat, 3 Aug 2024 16:25:18 +0530 Subject: [PATCH 11/22] fix [sellerController]: undo changes to token logic --- controllers/sellerController.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/controllers/sellerController.js b/controllers/sellerController.js index 801d52c..bc1f6c7 100644 --- a/controllers/sellerController.js +++ b/controllers/sellerController.js @@ -25,7 +25,7 @@ const sellerRegister = async (req, res) => { let result = await Seller.create(seller); result.password = undefined; - const token = createNewToken({ userId: result._id, userRole: result.role }) + const token = createNewToken(result._id) result = { ...result._doc, @@ -47,7 +47,7 @@ const sellerLogIn = async (req, res) => { if (validated) { seller.password = undefined; - const token = createNewToken({ userId: seller._id, userRole: seller.role }) + const token = createNewToken(seller._id) seller = { ...seller._doc, From a0ebd75f545a34c42eac5f6022354e9d8bfdb2c7 Mon Sep 17 00:00:00 2001 From: prakharCrudcook Date: Sat, 3 Aug 2024 16:30:33 +0530 Subject: [PATCH 12/22] fix [utils]: exported the fucntion to generate token --- utils/token.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/utils/token.js b/utils/token.js index 8575717..0cd267e 100644 --- a/utils/token.js +++ b/utils/token.js @@ -4,3 +4,5 @@ const createNewToken = (payload) => { return jwt.sign({ userId: payload }, process.env.SECRET_KEY, { expiresIn: '10d' }); } +module.exports = createNewToken; + From be7a427d831290f7929c50382dcbc691ac6954ed Mon Sep 17 00:00:00 2001 From: prakharCrudcook Date: Sat, 3 Aug 2024 16:32:53 +0530 Subject: [PATCH 13/22] fix [customerController]: fixed the conditions for checking customer existence --- controllers/customerController.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/controllers/customerController.js b/controllers/customerController.js index a7cacc7..da83f2a 100644 --- a/controllers/customerController.js +++ b/controllers/customerController.js @@ -38,9 +38,9 @@ const customerRegister = async (req, res) => { const customerLogIn = async (req, res) => { if (req.body.email && req.body.password) { let customer = await Customer.findOne({ email: req.body.email }); - if (!customer) { + if (customer) { const validated = await bcrypt.compare(req.body.password, customer.password); - if (!validated) { + if (validated) { customer.password = undefined; const token = createNewToken(customer._id) From 4a5d73917d2d2c5d610cae125524f2d49b898b85 Mon Sep 17 00:00:00 2001 From: prakharCrudcook Date: Sat, 3 Aug 2024 17:40:23 +0530 Subject: [PATCH 14/22] fix [sellerController]: added proper messaging for api and various checks --- controllers/sellerController.js | 70 ++++++++++++++++++++------------- middleware/authMiddleware.js | 9 +++-- 2 files changed, 48 insertions(+), 31 deletions(-) diff --git a/controllers/sellerController.js b/controllers/sellerController.js index bc1f6c7..292ab27 100644 --- a/controllers/sellerController.js +++ b/controllers/sellerController.js @@ -4,35 +4,45 @@ const createNewToken = require('../utils/token.js'); const sellerRegister = async (req, res) => { try { - const salt = await bcrypt.genSalt(10); - const hashedPass = await bcrypt.hash(req.body.password, salt); + const { email, password, name, shopName } = req.body; + if(!(email && password && name && shopName)) { + const salt = await bcrypt.genSalt(10); + const hashedPass = await bcrypt.hash(req.body.password, salt); - const seller = new Seller({ - ...req.body, - password: hashedPass - }); + const seller = new Seller({ + ...req.body, + password: hashedPass + // added hashed password + }); - const existingSellerByEmail = await Seller.findOne({ email: req.body.email }); - const existingShop = await Seller.findOne({ shopName: req.body.shopName }); + const existingSellerByEmail = await Seller.findOne({ email: req.body.email }); + const existingShop = await Seller.findOne({ shopName: req.body.shopName }); - if (existingSellerByEmail) { - res.send({ message: 'Email already exists' }); - } - else if (existingShop) { - res.send({ message: 'Shop name already exists' }); - } - else { - let result = await Seller.create(seller); - result.password = undefined; - - const token = createNewToken(result._id) + if (existingSellerByEmail) { + res.status(409).json({success: false, message: "Seller account already exists"}); + // added proper message and api consistency + } + else if (existingShop) { + res.status(409).json({success: false, message: "Shop already exists"}); + // added proper message and api consistency + } + else { + let result = await Seller.create(seller); + result.password = undefined; - result = { - ...result._doc, - token - }; + const token = createNewToken(result._id) - res.send(result); + result = { + ...result._doc, + token + }; + + // added proper message and api consistency + res.status(200).json({success: true, message: 'Seller Account Created.', result}); + } + } else { + res.status(401).json({success: false, message: 'Please provide the necessary details for accoutn creation!'}); + // added proper message and api consistency } } catch (err) { res.status(500).json(err); @@ -54,15 +64,19 @@ const sellerLogIn = async (req, res) => { token }; - res.send(seller); + res.status(200).json({success: true, message: 'Seller LogIn successful!'}) + // added proper message and api consistency } else { - res.send({ message: "Invalid password" }); + res.status(401).json({success: false, message: 'Invalid email or password!'}); + // added proper message and api consistency } } else { - res.send({ message: "User not found" }); + res.status(404).json({success: false, message: 'Seller account not found. Please signup.'}) + // added proper message and api consistency } } else { - res.send({ message: "Email and password are required" }); + res.status(401).json({success: false, message: 'Email and Password are required for login!'}); + // added proper message and api consistency } }; diff --git a/middleware/authMiddleware.js b/middleware/authMiddleware.js index 56969c9..a7bf72e 100644 --- a/middleware/authMiddleware.js +++ b/middleware/authMiddleware.js @@ -1,15 +1,18 @@ const jwt = require('jsonwebtoken'); +const dotenv = require("dotenv") +dotenv.config(); + const authMiddleware = (req, res, next) => { - const token = req.header('Authorization'); + const token = req.header('Authorization').split(' ')[1]; if (!token) { return res.status(401).json({ message: 'Authorization token not found' }); } try { - const decoded = jwt.env(token, process.env.SECRET_KEY); - req.user = decoded; + const decoded = jwt.verify(token, process.env.SECRET_KEY); + req.userId = decoded; next(); } catch (err) { return res.status(401).json({ message: 'Invalid token' }); From 2dc64caa0bf819e3acc3b064b017c779fc826b5f Mon Sep 17 00:00:00 2001 From: prakharCrudcook Date: Sat, 3 Aug 2024 18:39:16 +0530 Subject: [PATCH 15/22] fix [customerController, sellerController]: added proper checks and response messages for various apis --- controllers/customerController.js | 124 +++++++++++++++++------------- controllers/sellerController.js | 43 ++++++----- 2 files changed, 96 insertions(+), 71 deletions(-) diff --git a/controllers/customerController.js b/controllers/customerController.js index da83f2a..02824d7 100644 --- a/controllers/customerController.js +++ b/controllers/customerController.js @@ -1,91 +1,111 @@ const bcrypt = require('bcrypt'); const Customer = require('../models/customerSchema.js'); const createNewToken = require('../utils/token.js'); +const { reset } = require('nodemon'); +// fixed the import for createNewToken const customerRegister = async (req, res) => { try { - const salt = await bcrypt.genSalt(10); - const hashedPass = await bcrypt.hash(req.body.password, salt); + const { name, email, password } = req.body; + if(!(name && email && password)) { + const salt = await bcrypt.genSalt(10); + const hashedPass = await bcrypt.hash(req.body.password, salt); - const customer = new Customer({ - ...req.body, - password: hashedPass - }); + const customer = new Customer({ + ...req.body, + password: hashedPass + }); - const existingcustomerByEmail = await Customer.findOne({ email: req.body.email }); + const existingcustomerByEmail = await Customer.findOne({ email: req.body.email }); - if (existingcustomerByEmail) { - res.send({ message: 'Email already exists' }); - } - else { - let result = await Customer.create(customer); - result.password = undefined; - - const token = createNewToken(result._id) - - result = { - ...result._doc, - token: token - }; - - res.send(result); + if (existingcustomerByEmail) { + res.status(404).json({success: false, message: "Customer account already exists!"}); + // added proper messaging for api consistency + } + else { + let result = await Customer.create(customer); + result.password = undefined; + + const token = createNewToken(result._id) + + result = { + ...result._doc, + token: token + }; + + res.status(200).json({success: true, message: 'CUstomer account creation successful!', result}); + // added proper messaging for api consistency + } + } else { + res.status(401).json({success: false, message: 'Please provide the necessary details for account creation.'}); } + } catch (err) { - res.status(500).json(err); + res.status(500).json({success: false, message: 'Internal Server Error', err}); + // added proper messaging for api consistency } }; const customerLogIn = async (req, res) => { - if (req.body.email && req.body.password) { - let customer = await Customer.findOne({ email: req.body.email }); - if (customer) { - const validated = await bcrypt.compare(req.body.password, customer.password); - if (validated) { - customer.password = undefined; - - const token = createNewToken(customer._id) - - customer = { - ...customer._doc, - token: token - }; - - res.send(customer); + try{ + if (req.body.email && req.body.password) { + let customer = await Customer.findOne({ email: req.body.email }); + // changed condition for valid customer + if (customer) { + const validated = await bcrypt.compare(req.body.password, customer.password); + // changed condition check for correct password + if (validated) { + customer.password = undefined; + + const token = createNewToken(customer._id) + + customer = { + ...customer._doc, + token: token + }; + + res.status(200).json({success: true, message: 'Customer login successful!'}); + } else { + res.json(401).json({success: false, message: 'Invalid email or password.'}); + } } else { - res.send({ message: "Invalid password" }); + res.status(404).json({success: false, message: 'Customer account not found. Please signup.'}); } } else { - res.send({ message: "User not found" }); + res.send({ message: "Email and password are required" }); } - } else { - res.send({ message: "Email and password are required" }); + } catch(err) { + res.status(500).json({success: false, message: 'Internal Server Error.', err}); } }; const getCartDetail = async (req, res) => { try { - let customer = await Customer.findBy(req.params.id) + let customer = await Customer.findById(req.userId) // authMiddleware adds userId to request if (customer) { - res.get(customer.cartDetails); - } - else { - res.send({ message: "No customer found" }); + res.status(200).json({success: false, message: 'Customer cart details fetched.', cartDetails: customer.cartDetails}); + // if customer exists, we send the response with proper messaging } + res.status(404).json({success: false, message: 'Customer not found.'}); } catch (err) { - res.status(500).json(err); + res.status(500).json({success: false, message: 'Internal Server Error.', err}); } } const cartUpdate = async (req, res) => { try { + let customer = await Customer.findByIdAndUpdate(req.userId, req.body, { new: true }); + // getting id from token, and sending the new details - let customer = await Customer.findByIdAndUpdate(req.params.id, req.body, - { new: false }) + if(customer) { + return res.status(200).json({success: true, message: 'Customer cart updated!', updatedCart: customer}) + // if customer exists, we update and send the response with proper messaging + } - return res.send(customer.cartDetails); + res.status(404).json({success: false, message: 'Customer not found.'}); } catch (err) { - res.status(500).json(err); + res.status(500).json({success: false, message: 'Internal Server Error.', err); } } diff --git a/controllers/sellerController.js b/controllers/sellerController.js index 292ab27..0836df6 100644 --- a/controllers/sellerController.js +++ b/controllers/sellerController.js @@ -45,38 +45,43 @@ const sellerRegister = async (req, res) => { // added proper message and api consistency } } catch (err) { - res.status(500).json(err); + res.status(500).json({success: false, message: 'Internal Server Error.', err}); } }; const sellerLogIn = async (req, res) => { - if (req.body.email && req.body.password) { - let seller = await Seller.findOne({ email: req.body.email }); - if (seller) { - const validated = await bcrypt.compare(req.body.password, seller.password); - if (validated) { - seller.password = undefined; + try { + if (req.body.email && req.body.password) { + let seller = await Seller.findOne({ email: req.body.email }); + if (seller) { + const validated = await bcrypt.compare(req.body.password, seller.password); + if (validated) { + seller.password = undefined; - const token = createNewToken(seller._id) + const token = createNewToken(seller._id) - seller = { - ...seller._doc, - token - }; + seller = { + ...seller._doc, + token + // tokens->token + }; - res.status(200).json({success: true, message: 'Seller LogIn successful!'}) - // added proper message and api consistency + res.status(200).json({success: true, message: 'Seller LogIn successful!'}) + // added proper message and api consistency + } else { + res.status(401).json({success: false, message: 'Invalid email or password!'}); + // added proper message and api consistency + } } else { - res.status(401).json({success: false, message: 'Invalid email or password!'}); + res.status(404).json({success: false, message: 'Seller account not found. Please signup.'}) // added proper message and api consistency } } else { - res.status(404).json({success: false, message: 'Seller account not found. Please signup.'}) + res.status(401).json({success: false, message: 'Email and Password are required for login!'}); // added proper message and api consistency } - } else { - res.status(401).json({success: false, message: 'Email and Password are required for login!'}); - // added proper message and api consistency + } catch (err) { + res.status(500).json({success: false, message: 'Internal Server Error.', err}); } }; From 694b8de7c398366d6a00487cfa72d43f63b0abe9 Mon Sep 17 00:00:00 2001 From: prakharCrudcook Date: Sat, 3 Aug 2024 18:40:11 +0530 Subject: [PATCH 16/22] fix [customerController]: minor error --- controllers/customerController.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/controllers/customerController.js b/controllers/customerController.js index 02824d7..36c0003 100644 --- a/controllers/customerController.js +++ b/controllers/customerController.js @@ -98,14 +98,14 @@ const cartUpdate = async (req, res) => { // getting id from token, and sending the new details if(customer) { - return res.status(200).json({success: true, message: 'Customer cart updated!', updatedCart: customer}) + return res.status(200).json({success: true, message: 'Customer cart updated!', updatedCart: customer}); // if customer exists, we update and send the response with proper messaging } res.status(404).json({success: false, message: 'Customer not found.'}); } catch (err) { - res.status(500).json({success: false, message: 'Internal Server Error.', err); + res.status(500).json({success: false, message: 'Internal Server Error.', err}); } } From d12b12a89b2d86470aa282c13214b722942f3510 Mon Sep 17 00:00:00 2001 From: prakharCrudcook Date: Sat, 3 Aug 2024 18:41:23 +0530 Subject: [PATCH 17/22] fix [middlewar/authMiddleware]: added consistent api responses --- middleware/authMiddleware.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/middleware/authMiddleware.js b/middleware/authMiddleware.js index a7bf72e..bb5ddf8 100644 --- a/middleware/authMiddleware.js +++ b/middleware/authMiddleware.js @@ -7,7 +7,7 @@ const authMiddleware = (req, res, next) => { const token = req.header('Authorization').split(' ')[1]; if (!token) { - return res.status(401).json({ message: 'Authorization token not found' }); + return res.status(401).json({ success: false, message: 'Authorization token not found' }); } try { @@ -15,7 +15,7 @@ const authMiddleware = (req, res, next) => { req.userId = decoded; next(); } catch (err) { - return res.status(401).json({ message: 'Invalid token' }); + return res.status(401).json({success: false, message: 'Invalid token' }); } }; From ff401113ae597d89525ec306a5d92f2fa22764f3 Mon Sep 17 00:00:00 2001 From: prakharCrudcook Date: Sat, 3 Aug 2024 18:47:24 +0530 Subject: [PATCH 18/22] fix [routes, customerController]: add middleware to routes wherever required and updated controller function name --- controllers/customerController.js | 4 ++-- routes/route.js | 36 +++++++++++++++---------------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/controllers/customerController.js b/controllers/customerController.js index 36c0003..856c9d5 100644 --- a/controllers/customerController.js +++ b/controllers/customerController.js @@ -92,7 +92,7 @@ const getCartDetail = async (req, res) => { } } -const cartUpdate = async (req, res) => { +const customerUpdate = async (req, res) => { try { let customer = await Customer.findByIdAndUpdate(req.userId, req.body, { new: true }); // getting id from token, and sending the new details @@ -113,5 +113,5 @@ module.exports = { customerRegister, customerLogIn, getCartDetail, - cartUpdate, + customerUpdate, }; diff --git a/routes/route.js b/routes/route.js index 5ec706e..062e97f 100644 --- a/routes/route.js +++ b/routes/route.js @@ -26,7 +26,7 @@ const { customerRegister, customerLogIn, getCartDetail, - cartUpdate + customerUpdate // proper naming because we are updating customer not only cart } = require('../controllers/customerController.js'); const { @@ -40,30 +40,30 @@ router.post('/SellerRegister', sellerRegister); router.post('/SellerLogin', sellerLogIn); // Product -router.post('/ProductCreate', productCreate); -router.get('/getSellerProducts/:id', getSellerProducts); -router.get('/getProducts', getProducts); -router.get('/getProductDetail/:id', getProductDetail); -router.get('/getInterestedCustomers/:id', getInterestedCustomers); -router.get('/getAddedToCartProducts/:id', getAddedToCartProducts); +router.post('/ProductCreate', authMiddleware, productCreate); +router.get('/getSellerProducts/:id', getSellerProducts); // user can see product even without logging in but for more details, needs to login +router.get('/getProducts', authMiddleware, getProducts); +router.get('/getProductDetail/:id', authMiddleware, getProductDetail); +router.get('/getInterestedCustomers/:id', authMiddleware, getInterestedCustomers); +router.get('/getAddedToCartProducts/:id', authMiddleware, getAddedToCartProducts); -router.put('/ProductUpdate/:id', updateProduct); -router.put('/addReview/:id', addReview); +router.put('/ProductUpdate/:id', authMiddleware, updateProduct); +router.put('/addReview/:id', authMiddleware, addReview); -router.get('/searchProduct/:key', searchProductbyCategory); -router.get('/searchProductbyCategory/:key', searchProductbyCategory); -router.get('/searchProductbySubCategory/:key', searchProductbyCategory); +router.get('/searchProduct/:key', authMiddleware, searchProductbyCategory); +router.get('/searchProductbyCategory/:key', authMiddleware, searchProductbyCategory); +router.get('/searchProductbySubCategory/:key', authMiddleware, searchProductbyCategory); -router.delete('/DeleteProduct/:id', deleteProduct); -router.delete('/DeleteProducts/:id', deleteProducts); -router.delete ('/deleteProductReview/:id', deleteProductReview); -router.put ('/deleteAllProductReviews/:id', deleteAllProductReviews); +router.delete('/DeleteProduct/:id', authMiddleware, deleteProduct); +router.delete('/DeleteProducts/:id', authMiddleware, deleteProducts); +router.delete ('/deleteProductReview/:id', authMiddleware, deleteProductReview); +router.put ('/deleteAllProductReviews/:id', authMiddleware, deleteAllProductReviews); // Customer router.post('/CustomerRegister', customerRegister); router.post('/CustomerLogin', customerLogIn); -router.get('/getCartDetail/:id', getCartDetail); -router.put('/CustomerUpdate/:id', cartUpdate); +router.get('/getCartDetail', authMiddleware, getCartDetail); // we already have the userId through the jwt tokens +router.put('/CustomerUpdate', authMiddleware, customerUpdate); // we already have the userId through the jwt tokens // Order router.post('/newOrder', newOrder); From 9b7d88210eb68f9508e21c944059ea6fead9b2aa Mon Sep 17 00:00:00 2001 From: prakharCrudcook Date: Sat, 3 Aug 2024 18:48:31 +0530 Subject: [PATCH 19/22] uncommitted changes in prev commit --- controllers/productController.js | 2 +- routes/route.js | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/controllers/productController.js b/controllers/productController.js index 22d63f8..f39fbd4 100644 --- a/controllers/productController.js +++ b/controllers/productController.js @@ -5,7 +5,7 @@ const productCreate = async (req, res) => { try { const product = new Product(req.body) - let result = await product.save(); + let result = await Product.create(product); res.send(result); } catch (err) { diff --git a/routes/route.js b/routes/route.js index 062e97f..051dc0e 100644 --- a/routes/route.js +++ b/routes/route.js @@ -66,8 +66,8 @@ router.get('/getCartDetail', authMiddleware, getCartDetail); // we already have router.put('/CustomerUpdate', authMiddleware, customerUpdate); // we already have the userId through the jwt tokens // Order -router.post('/newOrder', newOrder); -router.get('/getOrderedProductsByCustomer/:id', getOrderedProductsBySeller); -router.get('/getOrderedProductsBySeller/:id', getOrderedProductsBySeller); +router.post('/newOrder', authMiddleware, newOrder); +router.get('/getOrderedProductsByCustomer/:id', authMiddleware, getOrderedProductsBySeller); +router.get('/getOrderedProductsBySeller/:id', authMiddleware, getOrderedProductsBySeller); module.exports = router; From 5ca16f2c96a0893619855c2f0daad03fa4499f39 Mon Sep 17 00:00:00 2001 From: prakharCrudcook Date: Sat, 3 Aug 2024 19:11:53 +0530 Subject: [PATCH 20/22] fix [orderController]: add checks and proper messaging --- controllers/orderController.js | 120 +++++++++++++++++++++------------ models/customerSchema.js | 2 +- 2 files changed, 79 insertions(+), 43 deletions(-) diff --git a/controllers/orderController.js b/controllers/orderController.js index 101c1ec..2b20126 100644 --- a/controllers/orderController.js +++ b/controllers/orderController.js @@ -1,31 +1,35 @@ const Order = require('../models/orderSchema.js'); +const Customer = require('../models/customerSchema.js') const newOrder = async (req, res) => { try { + const customerId = req.userId; - const { - buyer, - shippingData, - orderedProducts, - paymentInfo, - productsQuantity, - totalPrice, - } = req.body; - - const order = await Order.create({ - buyer, - shippingData, - orderedProducts, - paymentInfo, - paidAt: Date.now(), - productsQuantity, - totalPrice, - }); - - return res.send(order); + const customer = Customer.findById(customerId); + if(customer) { + const { + shippingData, + orderedProducts, + paymentInfo, + productsQuantity, + totalPrice, + } = req.body; + const order = await Order.create({ + buyer: customer, // we can get buyer deatils from the customer details we extracted + shippingData, + orderedProducts, + paymentInfo, + paidAt: Date.now(), + productsQuantity, + totalPrice, + }); + + return res.status(200).json({success: true, message: 'Customer order placed successfully.', order}); + } + res.status(404).json({success: false, message: 'Customer account not found.'}); } catch (err) { - res.status(500).json(err); + res.status(500).json({success: false, message: 'Internal Server Error.', err}); } } @@ -33,39 +37,67 @@ const secretDebugValue = "Don't forget to check the time zone!"; const getOrderedProductsByCustomer = async (req, res) => { try { - let orders = await Order.find({ buyer: req.params.id }); - + const customerId = req.userId; + const customer = await Customer.findById(customerId); + if (!customer) { + return res.status(404).json({ success: false, message: 'Customer account not found.' }); + } + + const orders = await Order.find({ buyer: customerId }); + if (!orders || orders.length === 0) { + return res.status(404).json({ success: false, message: 'No orders found for this customer.' }); + } + const orderedProducts = orders.reduce((accumulator, order) => { - - return accumulator.filter(product => { - accumulator.push(...order.orderedProducts); - return true; - }); + return accumulator.concat(order.orderedProducts); }, []); - + if (orderedProducts.length > 0) { - res.send(orderedProducts); + return res.json({ success: true, orderedProducts }); } else { - - res.send({ message: "No products found. Check the filtering logic." }); + return res.json({ success: false, message: "No products found. Check the filtering logic." }); } } catch (err) { - res.status(500).json(err); + return res.status(500).json({ success: false, message: 'Internal server error.', err}); } }; + const getOrderedProductsBySeller = async (req, res) => { try { const sellerId = req.params.id; + const customerId = req.userId; + const customer = await Customer.findById(customerId); + + if (!customer) { + return res.status(404).json({ success: false, message: 'Customer account not found.' }); + } + + + // Find orders where orderedProducts contain the sellerId const ordersWithSellerId = await Order.find({ 'orderedProducts.sellerId': sellerId }); - if (ordersWithSellerId.length > 0) { - const orderedProducts = ordersWithSellerId.reduce((accumulator, order) => { - order.orderedProducts.forEach(product => { + if (!ordersWithSellerId.length) { + return res.status(404).json({ success: false, message: "No orders found for this seller." }); + } + + // Filter orders by customer ID if provided + let filteredOrders = ordersWithSellerId; + if (customerId) { + filteredOrders = ordersWithSellerId.filter(order => order.buyer.toString() === customerId); + if (!filteredOrders.length) { + return res.status(404).json({ success: false, message: "No orders found for this seller and customer." }); + } + } + + // Aggregate ordered products + const orderedProducts = filteredOrders.reduce((accumulator, order) => { + order.orderedProducts.forEach(product => { + if (product.sellerId.toString() === sellerId) { const existingProductIndex = accumulator.findIndex(p => p._id.toString() === product._id.toString()); if (existingProductIndex !== -1) { // If product already exists, merge quantities @@ -74,18 +106,22 @@ const getOrderedProductsBySeller = async (req, res) => { // If product doesn't exist, add it to accumulator accumulator.push(product); } - }); - return accumulator; - }, []); - res.send(orderedProducts); + } + }); + return accumulator; + }, []); + + if (orderedProducts.length > 0) { + return res.json({ success: true, orderedProducts }); } else { - res.send({ message: "No products found" }); + return res.json({ success: false, message: "No products found." }); } } catch (err) { - res.status(500).json(err); + return res.status(500).json({ success: false, message: 'Internal server error.', error: err.message }); } }; + module.exports = { newOrder, getOrderedProductsByCustomer, diff --git a/models/customerSchema.js b/models/customerSchema.js index c2fcdc6..34cefc8 100644 --- a/models/customerSchema.js +++ b/models/customerSchema.js @@ -1,6 +1,6 @@ const mongoose = require("mongoose") -const customerSchema = mongoose.Schema({ +const customerSchema = new mongoose.Schema({ name: { type: String, required: true, From bf20edab3ad2660fa786558c4667da3fb7bddbb5 Mon Sep 17 00:00:00 2001 From: prakharCrudcook Date: Sat, 3 Aug 2024 19:17:14 +0530 Subject: [PATCH 21/22] fix [database]: remove unnecessary code --- database.js | 292 +--------------------------------------------------- 1 file changed, 5 insertions(+), 287 deletions(-) diff --git a/database.js b/database.js index 3e88a81..37f0f08 100644 --- a/database.js +++ b/database.js @@ -12,6 +12,11 @@ Setting up the database. This might take a moment. Note: It worked if it ends with "Dummy data created!" `) +const Customer = require('./models/customerSchema.js'); +const Order = require('./models/orderSchema.js'); +const Product = require("./models/productSchema"); +const Seller = require('./models/sellerSchema.js'); + // Connect to MongoDB mongoose.connect(mongoURL, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { @@ -20,292 +25,6 @@ mongoose.connect(mongoURL, { useNewUrlParser: true, useUnifiedTopology: true }) }) .catch(err => console.log(err)); -// Customer Schema -const customerSchema = new mongoose.Schema({ - name: { - type: String, - required: true, - }, - email: { - type: String, - unique: true, - required: true, - }, - password: { - type: String, - required: true, - }, - role: { - type: String, - default: "Customer" - }, - cartDetails: [{ - productName: { - type: String - }, - price: { - mrp: { - type: Number - }, - cost: { - type: Number - }, - discountPercent: { - type: Number - } - }, - subcategory: { - type: String - }, - productImage: { - type: String - }, - category: { - type: String - }, - description: { - type: String - }, - tagline: { - type: String - }, - quantity: { - type: Number - }, - seller: { - type: mongoose.Schema.Types.ObjectId, - ref: 'seller' - }, - }], - shippingData: { - address: { - type: String, - }, - city: { - type: String, - }, - state: { - type: String, - }, - country: { - type: String, - }, - pinCode: { - type: Number, - }, - phoneNo: { - type: Number, - }, - } -}); - -const Customer = mongoose.model("customer", customerSchema); - -// Order Schema -const orderSchema = new mongoose.Schema({ - buyer: { - type: mongoose.Schema.ObjectId, - ref: "customer", - required: true, - }, - shippingData: { - address: { - type: String, - required: true, - }, - city: { - type: String, - required: true, - }, - state: { - type: String, - required: true, - }, - country: { - type: String, - required: true, - }, - pinCode: { - type: Number, - required: true, - }, - phoneNo: { - type: Number, - required: true, - }, - }, - orderedProducts: [{ - productName: { - type: String - }, - price: { - mrp: { - type: Number - }, - cost: { - type: Number - }, - discountPercent: { - type: Number - } - }, - subcategory: { - type: String - }, - productImage: { - type: String - }, - category: { - type: String - }, - description: { - type: String - }, - tagline: { - type: String - }, - quantity: { - type: Number - }, - seller: { - type: mongoose.Schema.Types.ObjectId, - ref: 'seller' - }, - }], - paymentInfo: { - id: { - type: String, - required: true, - }, - status: { - type: String, - required: true, - }, - }, - paidAt: { - type: Date, - required: true, - }, - productsQuantity: { - type: Number, - required: true, - default: 0, - }, - taxPrice: { - type: Number, - required: true, - default: 0, - }, - shippingPrice: { - type: Number, - required: true, - default: 0, - }, - totalPrice: { - type: Number, - required: true, - default: 0, - }, - orderStatus: { - type: String, - required: true, - default: "Processing", - }, - deliveredAt: Date, - createdAt: { - type: Date, - default: Date.now, - }, -}); - -const Order = mongoose.model("order", orderSchema); - -// Product Schema -const productSchema = new mongoose.Schema({ - productName: { - type: String - }, - price: { - mrp: { - type: Number - }, - cost: { - type: Number - }, - discountPercent: { - type: Number - } - }, - subcategory: { - type: String - }, - productImage: { - type: String - }, - category: { - type: String - }, - description: { - type: String - }, - tagline: { - type: String - }, - quantity: { - type: Number, - default: 1 - }, - reviews: [{ - rating: { - type: Number, - }, - comment: { - type: String, - }, - reviewer: { - type: mongoose.Schema.Types.ObjectId, - ref: "customer", - }, - date: { - type: Date, - default: Date.now, - }, - }], - seller: { - type: mongoose.Schema.Types.ObjectId, - ref: 'seller' - }, -}, { timestamps: true }); - -const Product = mongoose.model("product", productSchema); - -// Seller Schema -const sellerSchema = new mongoose.Schema({ - name: { - type: String, - required: true, - }, - email: { - type: String, - unique: true, - required: true, - }, - password: { - type: String, - required: true, - }, - role: { - type: String, - default: "Seller" - }, - shopName: { - type: String, - unique: true, - required: true - } -}); - -const Seller = mongoose.model("seller", sellerSchema); // Function to create dummy data async function createDummyData() { @@ -382,4 +101,3 @@ async function createDummyData() { console.log('Dummy data created!'); } -module.exports = { Customer, Order, Product, Seller }; From 203247b81ea34e3deef669f59793f4bcd917d07e Mon Sep 17 00:00:00 2001 From: prakharCrudcook Date: Sat, 3 Aug 2024 19:53:11 +0530 Subject: [PATCH 22/22] Updated README --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 971310e..8d6e180 100644 --- a/README.md +++ b/README.md @@ -238,3 +238,7 @@ To set up the database schema, follow these steps:
IEEE CS MUJ Logo
+ + + +Google Sheet: https://docs.google.com/spreadsheets/d/1Yngwstkeb8a3PK_3yxw_tf7FwizE5HyiCU8LfL77UYY/edit?usp=sharing