From 22e323e291ac6ce3bfe695649e713d71544513ed Mon Sep 17 00:00:00 2001
From: sumanmondal11 <mithumondal546@gmail.com>
Date: Fri, 21 Apr 2023 15:19:34 -0400
Subject: [PATCH] login

---
 backend/middlewares/userMiddleware.js         | 27 +++++++++++++-----
 backend/routes/user.js                        |  8 ++++--
 client/src/App.js                             | 21 ++++++++------
 client/src/components/routes/CustomerRoute.js | 28 +++++++++++++++++++
 client/src/components/routes/Loading.js       | 21 ++++++++++----
 client/src/pages/Checkout.js                  |  2 +-
 6 files changed, 81 insertions(+), 26 deletions(-)
 create mode 100644 client/src/components/routes/CustomerRoute.js

diff --git a/backend/middlewares/userMiddleware.js b/backend/middlewares/userMiddleware.js
index 5953c8ca..c408de5f 100644
--- a/backend/middlewares/userMiddleware.js
+++ b/backend/middlewares/userMiddleware.js
@@ -13,16 +13,29 @@ const requireSignIn = (req, res, next) => {
     }
 }
 const isCustomer = async (req, res, next) => {
-    const user = await User.findById(req.user.id);
-    if (user.role !== 0) {
-        console.log(req.user.role)
-        return res.status(403).json({
-            error: "Access denied. You are not authorized to perform this action.",
-        });
+    try {
+        const token = req.headers.authorization;
+        if (!token) {
+            return next();
+        }
+        const decoded = jwt.verify(token, process.env.JWT_SECRET);
+        req.user = decoded;
+        const user = await User.findById(decoded.id);
+        if (user.role === 1) {
+            return res.status(403).json({ ok: false });
+        }
+        next();
+    } catch (err) {
+        if (err.name === 'JsonWebTokenError') {
+            return res.status(401).json({ error: 'Invalid token.' });
+        }
+        console.log(err);
+        return res.status(500).json({ error: 'Server error.' });
     }
-    next();
 };
 
+
+
 const isAdmin = async (req, res, next) => {
     try {
         const user = await User.findById(req.user.id);
diff --git a/backend/routes/user.js b/backend/routes/user.js
index a8712e70..9f4fc7d1 100644
--- a/backend/routes/user.js
+++ b/backend/routes/user.js
@@ -12,14 +12,14 @@ const {
   loginAdmin,
   getOrders,
 } = require("../controllers/userController");
-const { requireSignIn, isAdmin } = require("../middlewares/userMiddleware");
+const { requireSignIn, isAdmin, isCustomer} = require("../middlewares/userMiddleware");
 
 router.post("/signup", createUser);
 router.post("/login", loginUser);
 router.post("/admin", loginAdmin);
 
 // only for testing login is required features
-router.get("/secret", requireSignIn, isAdmin, secret);
+router.get("/secret", isCustomer, verified);
 
 //can be used in the future (these paths are giving errors when trying to fetch all the products, categories, and subcategories)
 // router.get('/', getUsers);
@@ -30,8 +30,10 @@ router.delete("/:id", deleteUser);
 
 //authenticate users as admin and requireSignIn
 router.get("/auth-Check", requireSignIn, verified);
-
 router.get("/admin-check", requireSignIn, isAdmin, verified);
+router.get("/customer-check", isCustomer, verified);
+
 router.get("/orders/:id", requireSignIn, getOrders);
 
+
 module.exports = router;
diff --git a/client/src/App.js b/client/src/App.js
index 03e5fd01..433d08cd 100644
--- a/client/src/App.js
+++ b/client/src/App.js
@@ -16,6 +16,7 @@ import "react-toastify/dist/ReactToastify.css";
 import ProductDetailPage from "./pages/ProductDetailPage";
 import PrivateRoute from "./components/routes/PrivateRoute";
 import AdminRoute from "./components/routes/AdminRoute";
+import CustomerRoute from "./components/routes/CustomerRoute";
 import ProductViewPage from "./pages/ProductViewPage";
 import ProductUpdatePage from "./pages/ProductUpdatePage";
 import CategoryPage from "./pages/CategoryPage";
@@ -31,21 +32,22 @@ function App() {
     <>
       <ToastContainer position="top-center" />
       <Routes>
-        <Route index element={<HomePage />} />
         <Route path="/login" element={<LoginPage />} />
         <Route path="/signup" element={<SignupPage />} />
         <Route path="/search" element={<Search />} />
-        <Route path="/wishlist" element={<WishlistPage />} />
-        <Route path="/category/:category" element={<CategoryPage />} />
         <Route path="/admin" element={<AdminLoginPage />} />
 
 
-        <Route
-          path="/:category/products/:subcategory"
-          element={<ProductPage />}
-        />
-        <Route path="/products/:id" element={<ProductDetailPage />} />
-        <Route path="/admin/product/view" element={<ProductViewPage />} />
+        {/*Customer Route*/}
+        <Route path="/" element={<CustomerRoute />}>
+          <Route path="/category/:category" element={<CategoryPage />} />
+          <Route index element={<HomePage />} />
+          <Route
+              path="/:category/products/:subcategory"
+              element={<ProductPage />}
+          />
+          <Route path="/products/:id" element={<ProductDetailPage />} />
+        </Route>
 
         {/*Private routes*/}
         <Route path="/" element={<PrivateRoute />}>
@@ -65,6 +67,7 @@ function App() {
             path="subcategory/update/:slug"
             element={<SubCategoryUpdatePage />}
           />
+          <Route path="product/view" element={<ProductViewPage />} />
           <Route
             path="product/update/:productId"
             element={<ProductUpdatePage />}
diff --git a/client/src/components/routes/CustomerRoute.js b/client/src/components/routes/CustomerRoute.js
new file mode 100644
index 00000000..00c1cfcb
--- /dev/null
+++ b/client/src/components/routes/CustomerRoute.js
@@ -0,0 +1,28 @@
+import React, { useEffect, useState } from "react";
+import { Outlet, Navigate } from "react-router-dom";
+import { useAuth } from "../../context/auth";
+import Loading from "./Loading";
+import axios from "axios";
+
+const CustomerRoute = () => {
+    const [auth] = useAuth();
+    const [ok, setOk] = useState(true);
+
+    useEffect(() => {
+        const customerCheck = async () => {
+            const { data } = await axios.get(`/customer-check`);
+            console.log(data);
+            if (data.ok) {
+                setOk(true);
+            } else {
+                setOk(false);
+            }
+        };
+
+        if (auth.token) customerCheck();
+    }, [auth.token]);
+
+    return ok ? <Outlet /> : <Loading />;
+};
+
+export default CustomerRoute;
diff --git a/client/src/components/routes/Loading.js b/client/src/components/routes/Loading.js
index 782b70c2..c7364639 100644
--- a/client/src/components/routes/Loading.js
+++ b/client/src/components/routes/Loading.js
@@ -6,18 +6,27 @@ export default function Loading() {
     const [count, setCount] = useState(3);
     const navigate = useNavigate();
     const location = useLocation();
+
     useEffect(()=> {
         const interval = setInterval(() => {
             setCount((currentCount) => --currentCount);
         }, 500);
-        count === 0 && navigate("/login", {
-            state: location.pathname
-        })
-        return ()=> clearInterval(interval)
-    }, [count])
+
+        if (location.pathname.startsWith("/admin")) {
+            count === 0 && navigate("/admin", {
+                state: location.pathname
+            });
+        } else {
+            count === 0 && navigate("/login", {
+                state: location.pathname
+            });
+        }
+
+        return () => clearInterval(interval);
+    }, [count, navigate, location.pathname]);
 
     return (
-        <div className= "d-flex justify-content-center align-items-center vh-100">
+        <div className="d-flex justify-content-center align-items-center vh-100">
             <img src={LoadingGIF} alt="Loading"/>
             <br/>
             <h1>Login Required.</h1>
diff --git a/client/src/pages/Checkout.js b/client/src/pages/Checkout.js
index 9aef864b..7b174de4 100644
--- a/client/src/pages/Checkout.js
+++ b/client/src/pages/Checkout.js
@@ -23,7 +23,7 @@ const Checkout = () => {
 
   const handleCloseModal = () => setShowModal(false);
   const handleShowModal = () => setShowModal(true);
-  const totalAmount = getCartTotal();git
+  const totalAmount = getCartTotal();
 
   const navigate = useNavigate();
   const location = useLocation();
-- 
GitLab