Skip to content

Commit

Permalink
Merge pull request #421 from Sourabh782/session
Browse files Browse the repository at this point in the history
Implemented session management #144
  • Loading branch information
RamakrushnaBiswal authored Oct 29, 2024
2 parents 2a02400 + aae2662 commit 4156b76
Show file tree
Hide file tree
Showing 10 changed files with 76 additions and 10 deletions.
28 changes: 25 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,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",
Expand All @@ -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" });
}
}
Expand Down Expand Up @@ -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
};
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
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/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
10 changes: 9 additions & 1 deletion frontend/src/components/Shared/Navbar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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: '/' },
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 4156b76

Please sign in to comment.