Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
haseebzaki-07 committed Oct 29, 2024
2 parents 7df9c25 + 1df68f2 commit c044a97
Show file tree
Hide file tree
Showing 22 changed files with 411 additions and 208 deletions.
29 changes: 26 additions & 3 deletions backend/controller/customer.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -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" });
}
Expand All @@ -123,7 +123,19 @@ async function loginCustomer(req, res) {
process.env.JWT_SECRET,
{ expiresIn: "1h" } // Expires in 1 hour
);
res.json({

req.session.user = {
id: customer._id,
name: customer.name,
};

res.cookie("authToken", token, {
maxAge: 1000 * 60 * 60,
httpOnly: true,
secure: true,
});

return res.json({
message: "Login successful",
token,
role: "customer",
Expand All @@ -135,6 +147,7 @@ async function loginCustomer(req, res) {
});
} catch (error) {
console.error("Error during login:", error);

res.status(500).json({ error: "Internal server error" });
}
}
Expand Down Expand Up @@ -165,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
};
17 changes: 17 additions & 0 deletions backend/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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"));

Expand Down
48 changes: 15 additions & 33 deletions backend/middlewares/authCustomer.js
Original file line number Diff line number Diff line change
@@ -1,42 +1,24 @@
const jwt = require("jsonwebtoken");
const logger = require("../config/logger");
const config = require("../config/secret");
const Customer = require("../models/customer.model");
// Assuming the Customer model is located here

const authenticateCustomer = async (req, res, next) => {
const authenticateCustomer = (req, res, next) => {
const token = req.header("Authorization")?.split(" ")[1]; // Expecting "Bearer <token>"

if (!token) {
return res.status(401).json({ message: "Authorization token is missing" });
}

try {
// Verify token
const decoded = jwt.verify(token, config.JWT_SECRET);

// Retrieve user from database to check verification status
const user = await Customer.findById(decoded.sub);

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

if (!user.isVerified) {
return res.status(403).json({ message: "Account not verified" });
}

// If verified, attach user to request and proceed
req.user = user;
logger.info(`Customer authenticated: ${user.name}`);
next();

} catch (err) {
if (err.name === "TokenExpiredError") {
return res.status(401).json({ message: "Token expired" });
}
logger.error("Token verification failed:", err);
return res.status(403).json({ message: "Invalid token" });
if (token) {
jwt.verify(token, config.JWT_SECRET, (err, user) => {
if (err) {
if (err.name === "TokenExpiredError") {
return res.status(401).json({ message: "Token expired" });
}
return res.status(403).json({ message: "Invalid token" });
}
req.user = user;
logger.info(`Customer authenticated: ${JSON.stringify(user.username)}`);
next();
});
} else {
res.sendStatus(401); // Unauthorized
}
};

Expand Down
12 changes: 12 additions & 0 deletions backend/middlewares/sessionMiddleware.js
Original file line number Diff line number Diff line change
@@ -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;
2 changes: 2 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 2 additions & 0 deletions backend/routes/customerRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const {
loginCustomer,
createCustomer,
resetPassword,
logout,
verifyOtp,
} = require("../controller/customer.controller");
const authenticateCustomer = require("../middlewares/authCustomer");
Expand All @@ -28,6 +29,7 @@ router.get(
);

router.post("/register", createCustomer);
router.post("/logout", logout)
router.post("/verify", verifyOtp);
router.get(
"/auth/google",
Expand Down
3 changes: 2 additions & 1 deletion backend/routes/eventRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ const {
getEvents,
deleteEvent,
} = require("../controller/event.controller");
const authenticateCustomer = require("../middlewares/authCustomer");

const router = express.Router();

Expand All @@ -26,8 +25,10 @@ router.get("/", async (req, res) => {
}
});


router.post("/create",authenticateCustomer, createEvent);
router.get("/all",authenticateCustomer, getEvents);
router.get("/delete",authenticateCustomer, deleteEvent);


module.exports = router;
3 changes: 2 additions & 1 deletion backend/routes/feedbackRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion backend/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
Expand Down
7 changes: 4 additions & 3 deletions backend/routes/orderRouter.js
Original file line number Diff line number Diff line change
@@ -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;
3 changes: 2 additions & 1 deletion backend/routes/reservationRouter.js
Original file line number Diff line number Diff line change
@@ -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!",
Expand Down
2 changes: 2 additions & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,14 @@
"framer-motion": "^11.5.6",
"gsap": "^3.12.5",
"js-cookie": "^3.0.5",
"lucide-react": "^0.454.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-icons": "^5.2.1",
"react-intersection-observer": "^9.13.0",
"react-lazy-load-image-component": "^1.6.2",
"react-pageflip": "^2.0.3",
"react-responsive": "^10.0.0",
"react-router-dom": "^6.24.1",
"split-type": "^0.3.4",
"tailwind-merge": "^2.5.2",
Expand Down
Binary file added frontend/src/assets/Boardgames/CARROM.webp
Binary file not shown.
16 changes: 14 additions & 2 deletions frontend/src/components/Pages/Boardgame.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React, { useState,useEffect } from 'react';
import { Splide, SplideSlide } from '@splidejs/react-splide';
import { AutoScroll } from '@splidejs/splide-extension-auto-scroll';
import '@splidejs/react-splide/css';

import CARROM from '../../assets/Boardgames/CARROM.webp';
import board1 from '../../assets/Boardgames/board1.png';
import board2 from '../../assets/Boardgames/board2.png';
import board3 from '../../assets/Boardgames/board3.jpg';
Expand Down Expand Up @@ -283,7 +283,19 @@ function Boardgame() {
"In case of a tie, a 'war' occurs: each player places three cards face down and reveals the next card. The higher card wins all the cards on the table.",
"The game continues until one player has all the cards or until players decide to stop."
]
}
},
// CARROM ADDED
{
"src": CARROM,
"title": "Carrom",
"description": "A popular tabletop game where players use a striker to pocket pieces into four corner pockets.",
"instructions": [
"Players take turns flicking the striker to pocket carrom men (game pieces) into the corner pockets.",
"Each player aims to score points by pocketing their assigned pieces (black or white) and the queen piece.",
"The queen is the red piece, and it must be followed by another pocketed piece to be claimed.",
"The game continues until all pieces are pocketed, and the player with the highest score wins."
],
},


];
Expand Down
16 changes: 1 addition & 15 deletions frontend/src/components/Pages/Event.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ import game from '../../assets/Boardgames/carrom.gif';
import spin from '../../assets/Boardgames/spin.gif';
import MainHOC from '../MainHOC';
const daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
import { useNavigate } from 'react-router-dom';
import Cookies from 'js-cookie';
const months = [
'January',
'February',
Expand All @@ -33,18 +31,6 @@ const months = [
function Event() {
const [events, setEvents] = useState([]);
const [error, setError] = useState(null);
const navigate = useNavigate();



const handleRegisterClick = () => {
const isAuthenticated = Boolean(Cookies.get('authToken'));

if (!isAuthenticated) {
alert("Please sign in to register for the event.");
navigate('/login');
}
};
useEffect(() => {
const fetchData = async () => {
try {
Expand Down Expand Up @@ -197,7 +183,7 @@ function Event() {
))}
</div>
<div className="text-center mt-4">
<button onClick={handleRegisterClick} className="bg-[#FEF3C7] dark:bg-black text-gray-700 dark:text-white px-4 py-2 rounded-md mt-4">
<button className="bg-[#FEF3C7] dark:bg-black text-gray-700 dark:text-white px-4 py-2 rounded-md mt-4">
Register for Event
</button>
</div>
Expand Down
Loading

0 comments on commit c044a97

Please sign in to comment.