Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 73 additions & 19 deletions admin/src/App.jsx
Original file line number Diff line number Diff line change
@@ -1,34 +1,88 @@
import React from "react";
import { Route, Routes } from "react-router-dom";
import React, { useContext } from "react";
import { Route, Routes, Navigate } from "react-router-dom";
import { ToastContainer } from "react-toastify";

import Home from "./pages/Home";
import Add from "./pages/Add";
import List from "./pages/List";
import Order from "./pages/Order";
import Login from "./pages/Login";
import { useContext } from "react";

import { adminDataContext } from "./Context/AdminProvider";
import { ToastContainer } from "react-toastify";

function ProtectedRoute({ children }) {
const { adminData } = useContext(adminDataContext);

if (!adminData) {
return <Navigate to="/login" replace />;
}

return children;
}

function App() {
let { adminData } = useContext(adminDataContext);
const { adminData } = useContext(adminDataContext);

return (
<>
<ToastContainer />
{!adminData ? (
<Login />
) : (
<>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/add" element={<Add />} />
<Route path="/list" element={<List />} />
<Route path="/order" element={<Order />} />
<Route path="/login" element={<Login />} />
</Routes>
</>
)}

<Routes>
<Route
path="/login"
element={
adminData ? <Navigate to="/" replace /> : <Login />
}
/>

<Route
path="/"
element={
<ProtectedRoute>
<Home />
</ProtectedRoute>
}
/>

<Route
path="/add"
element={
<ProtectedRoute>
<Add />
</ProtectedRoute>
}
/>

<Route
path="/list"
element={
<ProtectedRoute>
<List />
</ProtectedRoute>
}
/>

<Route
path="/order"
element={
<ProtectedRoute>
<Order />
</ProtectedRoute>
}
/>

<Route
path="*"
element={
<Navigate
to={adminData ? "/" : "/login"}
replace
/>
}
/>
</Routes>
</>
);
}

export default App;
export default App;
17 changes: 12 additions & 5 deletions backend/config/Token.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
import jwt from "jsonwebtoken";

export const genToken = (userId) => {
return jwt.sign({ userId }, process.env.JWT_SECRET, {
expiresIn: "7d",
});
export const genToken = (userId, role = "user") => {
return jwt.sign(
{
userId,
role,
},
process.env.JWT_SECRET,
{
expiresIn: "7d",
}
);
};

export const genToken1 = async (email) => {
Expand All @@ -15,4 +22,4 @@ export const genToken1 = async (email) => {
} catch (_error) {
console.log("token error");
}
};
};
6 changes: 3 additions & 3 deletions backend/controller/authcontroller.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export const verifyOTP = async (req, res) => {
type: "new_user",
});

const token = genToken(user._id);
const token = genToken(user._id, user.role);

res.cookie("token", token, {
httpOnly: true,
Expand Down Expand Up @@ -126,7 +126,7 @@ export const login = async (req, res) => {
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) return res.status(400).json({ message: "Invalid credentials" });

const token = genToken(user._id);
const token = genToken(user._id, user.role);
res.cookie("token", token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
Expand All @@ -150,7 +150,7 @@ export const googleLogin = async (req, res) => {
user = await User.create({ name, email });
}

const token = genToken(user._id);
const token = genToken(user._id, user.role);
res.cookie("token", token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
Expand Down
21 changes: 21 additions & 0 deletions backend/middleware/authorizeRoles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const authorizeRoles = (...allowedRoles) => {
return (req, res, next) => {
if (!req.role) {
return res.status(401).json({
success: false,
message: "Unauthorized",
});
}

if (!allowedRoles.includes(req.role)) {
return res.status(403).json({
success: false,
message: "Forbidden: Access denied",
});
}

next();
};
};

export default authorizeRoles;
5 changes: 4 additions & 1 deletion backend/middleware/isAuth.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,14 @@ const isAuth = (req, res, next) => {

try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);

req.userId = decoded.userId;
req.role = decoded.role;

next();
} catch (_error) {
return res.status(401).json({ message: "Invalid token" });
}
};

export default isAuth;
export default isAuth;
21 changes: 14 additions & 7 deletions backend/model/userModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,20 @@ const userSchema = new mongoose.Schema(
},

wishlist: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Product",
},
],
resetPasswordToken: String,
resetPasswordExpire: Date,
{
type: mongoose.Schema.Types.ObjectId,
ref: "Product",
},
],

role: {
type: String,
enum: ["user", "admin", "super_admin"],
default: "user",
},

resetPasswordToken: String,
resetPasswordExpire: Date,
},
{
timestamps: true,
Expand Down
88 changes: 62 additions & 26 deletions backend/routes/notificationRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,36 +55,72 @@ router.put("/read-all-admin", adminAuth, adminRateLimiter, async (req, res) => {
});

// PUT /api/notifications/:id/read - Mark single notification as read
router.put("/:id/read", async (req, res) => {
try {
const { id } = req.params;
const notification = await Notification.findById(id);
if (!notification) {
return res.status(404).json({ message: "Notification not found" });
}
router.put(
"/:id/read",
isAuth,
userRateLimiter,
async (req, res) => {
try {
const { id } = req.params;
const notification = await Notification.findById(id);

if (!notification) {
return res.status(404).json({ message: "Notification not found" });
}

notification.read = true;
await notification.save();
return res.status(200).json({ success: true, notification });
} catch (error) {
console.error("Error marking notification read:", error);
return res.status(500).json({ message: "Server error" });
// Ownership check: prevent users from modifying other users' notifications
if (
!notification.isAdmin &&
notification.userId?.toString() !== req.userId
) {
return res.status(403).json({
success: false,
message: "Forbidden: Access denied",
});
}

notification.read = true;
await notification.save();
return res.status(200).json({ success: true, notification });
} catch (error) {
console.error("Error marking notification read:", error);
return res.status(500).json({ message: "Server error" });
}
}
});
);

// DELETE /api/notifications/:id - Delete single notification
router.delete("/:id", async (req, res) => {
try {
const { id } = req.params;
const notification = await Notification.findByIdAndDelete(id);
if (!notification) {
return res.status(404).json({ message: "Notification not found" });
router.delete(
"/:id",
isAuth,
userRateLimiter,
async (req, res) => {
try {
const { id } = req.params;
const notification = await Notification.findById(id);

if (!notification) {
return res.status(404).json({ message: "Notification not found" });
}

// Ownership check: prevent users from deleting other users' notifications
if (
!notification.isAdmin &&
notification.userId?.toString() !== req.userId
) {
return res.status(403).json({
success: false,
message: "Forbidden: Access denied",
});
}

await notification.deleteOne();
return res.status(200).json({ success: true, message: "Notification deleted" });
} catch (error) {
console.error("Error deleting notification:", error);
return res.status(500).json({ message: "Server error" });
}
return res.status(200).json({ success: true, message: "Notification deleted" });
} catch (error) {
console.error("Error deleting notification:", error);
return res.status(500).json({ message: "Server error" });
}
});
);

export default router;
export default router;
2 changes: 2 additions & 0 deletions backend/routes/productRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ let productRoutes = express.Router();

productRoutes.post(
"/addproduct",
adminAuth,
adminRateLimiter,
upload.fields([
{ name: "image1", maxCount: 1 },
{ name: "image2", maxCount: 1 },
Expand Down
24 changes: 20 additions & 4 deletions backend/routes/userRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,27 @@ import express from "express";
import isAuth from "../middleware/isAuth.js";
import { getAdmin, getCurrentUser } from "../controller/userController.js";
import adminAuth from "../middleware/adminAuth.js";
import { userRateLimiter, adminRateLimiter } from "../middleware/rateLimiters.js";
import authorizeRoles from "../middleware/authorizeRoles.js";
import {
userRateLimiter,
adminRateLimiter,
} from "../middleware/rateLimiters.js";

let userRoutes = express.Router();

userRoutes.get("/getCurrentUser", isAuth, userRateLimiter, getCurrentUser);
userRoutes.get("/getadmin", adminAuth, adminRateLimiter, getAdmin);
userRoutes.get(
"/getCurrentUser",
isAuth,
userRateLimiter,
getCurrentUser
);

export default userRoutes;
userRoutes.get(
"/getadmin",
isAuth,
authorizeRoles("admin", "super_admin"),
adminRateLimiter,
getAdmin
);

export default userRoutes;