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:
+
+
+
+Google Sheet: https://docs.google.com/spreadsheets/d/1Yngwstkeb8a3PK_3yxw_tf7FwizE5HyiCU8LfL77UYY/edit?usp=sharing
diff --git a/controllers/customerController.js b/controllers/customerController.js
index 09911c6..856c9d5 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 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.save();
- 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) => {
+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
- 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});
}
}
@@ -93,5 +113,5 @@ module.exports = {
customerRegister,
customerLogIn,
getCartDetail,
- cartUpdate,
+ customerUpdate,
};
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/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/controllers/sellerController.js b/controllers/sellerController.js
index b9943bb..0836df6 100644
--- a/controllers/sellerController.js
+++ b/controllers/sellerController.js
@@ -1,68 +1,87 @@
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 {
- 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: bcrypt.hash
- });
+ 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.save();
- 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: 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);
+ 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: tokens
- };
+ seller = {
+ ...seller._doc,
+ token
+ // tokens->token
+ };
- res.send(seller);
+ 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.send({ message: "Invalid password" });
+ res.status(404).json({success: false, message: 'Seller account not found. Please signup.'})
+ // added proper message and api consistency
}
} else {
- res.send({ message: "User not found" });
+ res.status(401).json({success: false, message: 'Email and Password are required for login!'});
+ // added proper message and api consistency
}
- } else {
- res.send({ message: "Email and password are required" });
+ } catch (err) {
+ res.status(500).json({success: false, message: 'Internal Server Error.', err});
}
};
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 };
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())
diff --git a/middleware/authMiddleware.js b/middleware/authMiddleware.js
index 56969c9..bb5ddf8 100644
--- a/middleware/authMiddleware.js
+++ b/middleware/authMiddleware.js
@@ -1,18 +1,21 @@
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' });
+ return res.status(401).json({ success: false, 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' });
+ return res.status(401).json({success: false, message: 'Invalid token' });
}
};
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,
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
diff --git a/routes/route.js b/routes/route.js
index 7919542..051dc0e 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,
@@ -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,32 +40,34 @@ 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);
-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;
diff --git a/utils/token.js b/utils/token.js
index 855ef6c..0cd267e 100644
--- a/utils/token.js
+++ b/utils/token.js
@@ -1,6 +1,8 @@
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' });
}
+module.exports = createNewToken;
+