Create a middleware file middleware/admin.js:
1
2
3
4
5
6
7
8
function adminOnly(req, res, next) {
if (req.user.role !== 'admin') {
return res.status(403).json({ msg: 'Admin access required' });
}
next();
}
module.exports = adminOnly;
Use this together with your auth middleware.
Update routes/products.js:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const auth = require('../middleware/auth');
const adminOnly = require('../middleware/admin');
// Admin: Create product
router.post('/', auth, adminOnly, async (req, res) => {
const product = new Product(req.body);
await product.save();
res.status(201).json(product);
});
// Admin: Update product
router.put('/:id', auth, adminOnly, async (req, res) => {
const updated = await Product.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.json(updated);
});
// Admin: Delete product
router.delete('/:id', auth, adminOnly, async (req, res) => {
await Product.findByIdAndDelete(req.params.id);
res.json({ msg: 'Product deleted' });
});
Create routes/admin.js:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const adminOnly = require('../middleware/admin');
const Order = require('../models/Order');
// Get all orders
router.get('/orders', auth, adminOnly, async (req, res) => {
const orders = await Order.find().populate('user').populate('items.product');
res.json(orders);
});
// Update order status
router.put('/orders/:id', auth, adminOnly, async (req, res) => {
const order = await Order.findByIdAndUpdate(
req.params.id,
{ status: req.body.status },
{ new: true }
).populate('items.product');
res.json(order);
});
1
2
const adminRoutes = require('./routes/admin');
app.use('/api/admin', adminRoutes);
In MongoDB or in a script, set a user’s role to “admin”:
1
2
3
4
db.users.updateOne(
{ email: "admin@example.com" },
{ $set: { role: "admin" } }
)
Remember to login as an admin to get the correct JWT cookie.
Notes
- This is a backend-only panel — a real UI dashboard can be built later using React + Admin Template.
- Use status values like “processing”, “shipped”, and “delivered” to update orders.