diff --git a/backend/controller/customer.controller.js b/backend/controller/customer.controller.js index 73c25ceb..b6195ece 100644 --- a/backend/controller/customer.controller.js +++ b/backend/controller/customer.controller.js @@ -97,16 +97,16 @@ async function loginCustomer(req, res) { try { const customer = await Customer.findOne({ email: req.body.email }); + if (!customer) { return res.status(401).json({ error: "Invalid email or password" }); } - - // Check if the customer is verified if (!customer.isVerified) { return res.status(403).json({ error: "Account not verified. Please verify your email." }); } const validPassword = await bcrypt.compare(req.body.password, customer.password); + if (!validPassword) { return res.status(401).json({ error: "Invalid email or password" }); } @@ -123,8 +123,19 @@ async function loginCustomer(req, res) { process.env.JWT_SECRET, { expiresIn: "1h" } // Expires in 1 hour ); + + req.session.user = { + id: customer._id, + name: customer.name, + }; - res.json({ + res.cookie("authToken", token, { + maxAge: 1000 * 60 * 60, + httpOnly: true, + secure: true, + }); + + return res.json({ message: "Login successful", token, role: "customer", @@ -136,6 +147,7 @@ async function loginCustomer(req, res) { }); } catch (error) { console.error("Error during login:", error); + res.status(500).json({ error: "Internal server error" }); } } @@ -166,9 +178,19 @@ async function resetPassword(req, res) { } } +async function logout(req, res){ + req.session.destroy((err) => { + if (err) { + return res.status(500).send("Failed to log out."); + } + res.send("Logged out successfully!"); + }); +} + module.exports = { createCustomer, loginCustomer, resetPassword, + logout, verifyOtp }; diff --git a/backend/index.js b/backend/index.js index 76d882ac..5dfeab5a 100644 --- a/backend/index.js +++ b/backend/index.js @@ -9,6 +9,8 @@ const passport = require("passport"); const { handleGoogleOAuth } = require("./controller/googleOAuth.controller"); const app = express(); const port = process.env.PORT || 3000; +const session = require("express-session"); +const MongoStore = require("connect-mongo"); // CORS configuration const corsOptions = { @@ -42,6 +44,21 @@ mongoose // Initialize passport middleware app.use(passport.initialize()); +app.use( + session({ + secret: process.env.SECRET_KEY, + resave: false, + saveUninitialized: false, + cookie: { + maxAge: 1000 * 60 * 60 * 24, + secure: false, + }, + store: MongoStore.create({ + mongoUrl: process.env.MONGO_URI, + }), + }) +); + // API routes app.use("/api", require("./routes/index")); diff --git a/backend/middlewares/sessionMiddleware.js b/backend/middlewares/sessionMiddleware.js new file mode 100644 index 00000000..aefe6d89 --- /dev/null +++ b/backend/middlewares/sessionMiddleware.js @@ -0,0 +1,12 @@ +const sessionMiddleware = async (req, res, next)=>{ + console.log(req.session.user); + + + if (req.session.user !== undefined) { + next(); + } else { + res.status(401).send("Invalid session. Please log in again."); + } +} + +module.exports = sessionMiddleware; \ No newline at end of file diff --git a/backend/package.json b/backend/package.json index 763337ac..11a318f0 100644 --- a/backend/package.json +++ b/backend/package.json @@ -16,9 +16,11 @@ "description": "", "dependencies": { "bcrypt": "^5.1.1", + "connect-mongo": "^5.1.0", "cors": "^2.8.5", "dotenv": "^16.4.5", "express": "^4.21.0", + "express-session": "^1.18.1", "jsonwebtoken": "^9.0.2", "mongoose": "^8.7.0", "nodemailer": "^6.9.15", diff --git a/backend/routes/customerRouter.js b/backend/routes/customerRouter.js index 14802eef..d06c51bb 100644 --- a/backend/routes/customerRouter.js +++ b/backend/routes/customerRouter.js @@ -3,6 +3,7 @@ const { loginCustomer, createCustomer, resetPassword, + logout, verifyOtp, } = require("../controller/customer.controller"); const authenticateCustomer = require("../middlewares/authCustomer"); @@ -28,6 +29,7 @@ router.get( ); router.post("/register", createCustomer); +router.post("/logout", logout) router.post("/verify", verifyOtp); router.get( "/auth/google", diff --git a/backend/routes/feedbackRouter.js b/backend/routes/feedbackRouter.js index f43654f1..90e2bb56 100644 --- a/backend/routes/feedbackRouter.js +++ b/backend/routes/feedbackRouter.js @@ -3,8 +3,9 @@ const { createFeedback } = require("../controller/feedback.controller"); const router = express.Router(); const apiInfo = require("../config/api.info"); const logger = require("../config/logger"); // Import your logger +const sessionMiddleware = require("../middlewares/sessionMiddleware"); -router.post("/create", createFeedback); +router.post("/create", sessionMiddleware, createFeedback); router.get("/", (req, res) => { try { diff --git a/backend/routes/index.js b/backend/routes/index.js index bb18bae4..9b6ceae5 100644 --- a/backend/routes/index.js +++ b/backend/routes/index.js @@ -49,7 +49,7 @@ router.get("/", (req, res) => { router.use("/event", eventRouter); router.use("/admin", require("./adminRouter")); -router.use("/feedback", feedbackRouter); +router.use("/feedback", require("./feedbackRouter")); router.use("/user", require("./customerRouter")); router.use("/reservation", require("./reservationRouter")); router.use("/newsletter", require("./newsletterRoute")); diff --git a/backend/routes/orderRouter.js b/backend/routes/orderRouter.js index 591b2b8c..5d3e3563 100644 --- a/backend/routes/orderRouter.js +++ b/backend/routes/orderRouter.js @@ -1,11 +1,12 @@ const express = require("express"); const { createOrder, getOrders, deleteOrder } = require("../controller/order.controller.js"); +const sessionMiddleware = require("../middlewares/sessionMiddleware.js"); const router = express.Router(); -router.post("/create/:id", createOrder); -router.get("/get/:id", getOrders); -router.delete("/delete/:id", deleteOrder); +router.post("/create/:id", sessionMiddleware, createOrder); +router.get("/get/:id", sessionMiddleware, getOrders); +router.delete("/delete/:id", sessionMiddleware, deleteOrder); module.exports = router; diff --git a/backend/routes/reservationRouter.js b/backend/routes/reservationRouter.js index 0976496d..3e6dcfb2 100644 --- a/backend/routes/reservationRouter.js +++ b/backend/routes/reservationRouter.js @@ -1,8 +1,9 @@ const express = require("express"); const { createReservation } = require("../controller/reservation.controller"); +const sessionMiddleware = require("../middlewares/sessionMiddleware"); const router = express.Router(); -router.post("/create", createReservation); +router.post("/create", sessionMiddleware, createReservation); router.get("/", (req, res) => { res.json({ message: "Welcome to the restaurant reservation API!", diff --git a/frontend/src/components/Shared/Navbar.jsx b/frontend/src/components/Shared/Navbar.jsx index b09f7b27..e01dd381 100644 --- a/frontend/src/components/Shared/Navbar.jsx +++ b/frontend/src/components/Shared/Navbar.jsx @@ -13,6 +13,7 @@ const Navbar = () => { const [token, setToken] = useState(Cookies.get('authToken')); const location = useLocation(); const navigate = useNavigate(); // Correctly initialize useNavigate + const API_URL = import.meta.env.VITE_BACKEND_URL || 'http://localhost:3000'; const menuItems = [ { name: 'HOME', path: '/' }, @@ -43,9 +44,16 @@ const Navbar = () => { setIsMenuOpen(!isMenuOpen); }; - const handleLogout = () => { + const handleLogout = async () => { // setisloggedIn(false); // Set isLoggedIn to false on confirmation //managing log in , logout using jwt tokens + const response = await fetch(`${API_URL}/api/user/logout`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + }) + Cookies.remove('authToken'); setToken(null); setIsModalOpen(false); // Close the modal