From 3d9b4ad6678aca3e45838cc67acce04b2a656ed7 Mon Sep 17 00:00:00 2001 From: Nishant Kaushal <101548649+nishant0708@users.noreply.github.com> Date: Fri, 7 Jun 2024 02:52:28 +0530 Subject: [PATCH] updated add --- server/controllers/Auth.js | 19 +++-- server/middlewares/auth.js | 80 +++++++++--------- src/components/ModalForm.jsx | 6 +- src/pages/AddFoodItem.jsx | 143 ++++++++++++++++++++++++++++++++ src/pages/Home.jsx | 2 +- src/pages/Login.jsx | 156 +++++++++++------------------------ src/pages/MenuPage.jsx | 6 +- src/pages/SectionPage.jsx | 10 ++- src/pages/Signup.jsx | 11 ++- 9 files changed, 264 insertions(+), 169 deletions(-) create mode 100644 src/pages/AddFoodItem.jsx diff --git a/server/controllers/Auth.js b/server/controllers/Auth.js index 31e876c..011b907 100644 --- a/server/controllers/Auth.js +++ b/server/controllers/Auth.js @@ -198,14 +198,16 @@ exports.changeStudentPassword = async (req, res) => { //for canteens exports.canteenSignup = async (req, res) => { + console.log("Received signup request with data:", req.body); try { const { name, email, collegeName, accountType, password } = req.body; const existingCanteen = await Canteen.findOne({ email }); if (existingCanteen) { + console.log("User already exists with email:", email); return res.status(400).json({ success: false, - message: "User alredy exist", + message: "User already exists", }); } @@ -214,6 +216,7 @@ exports.canteenSignup = async (req, res) => { try { hashedPassword = await bcrypt.hash(password, 10); } catch (error) { + console.error("Error in hashing password:", error); return res.status(500).json({ success: false, message: "Error in hashing password", @@ -228,20 +231,26 @@ exports.canteenSignup = async (req, res) => { password: hashedPassword, }); + // Create a token + const token = jwt.sign({ id: canteen._id, email: canteen.email }, process.env.JWT_SECRET, { + expiresIn: '1h', // Set token expiration time as needed + }); + + console.log("User created successfully with ID:", canteen._id); return res.status(200).json({ success: true, - message: "User created succesfully", + message: "User created successfully", cantId: canteen._id, + token, }); } catch (error) { - console.error(error); + console.error("Error during user registration:", error); return res.status(500).json({ success: false, - message: "USer can not be registred", + message: "User cannot be registered", }); } }; - exports.canteenLogin = async (req, res) => { try { const { email, password } = req.body; diff --git a/server/middlewares/auth.js b/server/middlewares/auth.js index 66767a1..3d819c0 100644 --- a/server/middlewares/auth.js +++ b/server/middlewares/auth.js @@ -3,101 +3,99 @@ const User = require("../models/studentLoginInfo"); const jwt = require("jsonwebtoken"); require("dotenv").config(); -//auth +// Utility function to extract token from various sources +const extractToken = (req) => { + if (req.cookies && req.cookies.token) return req.cookies.token; + if (req.headers.authorization && req.headers.authorization.startsWith("Bearer")) { + return req.headers.authorization.split(" ")[1]; + } + if (req.headers.cookie) { + const cookies = req.headers.cookie.split("; ").reduce((acc, cookie) => { + const [key, value] = cookie.split("="); + acc[key] = value; + return acc; + }, {}); + return cookies.token; + } + return null; +}; + +// Auth middleware for canteen exports.auth = async (req, res, next) => { try { - //extract token - const token = - req.cookies?.token || - req?.header("Authorization") || - req?.header("Authorisation")?.replace("Bearer ", "") || - req?.headers?.cookie.split("=")[1]; - - //if token missing, then return response + const token = extractToken(req); if (!token) { return res.status(401).json({ success: false, - message: "TOken is missing", + message: "Token is missing", }); } - //verify the token + try { const decode = jwt.verify(token, process.env.JWT_SECRET); - //now check that user present in db or not const user = await Canteen.findById(decode.id); - if (!user) + if (!user) { return res.status(500).json({ success: false, - message: "invalid user ! try to login again", + message: "Invalid user! Try to login again", }); + } req.user = user; + next(); } catch (err) { - //verification - issue return res.status(401).json({ success: false, - message: "token is invalid", + message: "Token is invalid", }); } - next(); } catch (error) { return res.status(401).json({ success: false, - message: `Something went wrong while validating the token ${error.message}`, + message: `Something went wrong while validating the token: ${error.message}`, }); } }; +// Auth middleware for student exports.studentAuth = async (req, res, next) => { try { - // console.log(req); - // console.log(req.cookies); - //extract token - const token = - req.cookies?.token || - req?.header("Authorization") || - req?.header("Authorisation")?.replace("Bearer ", "") || - req?.headers?.cookie.split("=")[1]; - // console.log(token); - //if token missing, then return response + const token = extractToken(req); if (!token) { return res.status(401).json({ success: false, - message: "TOken is missing", + message: "Token is missing", }); } - //verify the token + try { const decode = jwt.verify(token, process.env.JWT_SECRET); - console.log(decode); - //now check that user present in db or not const user = await User.findById(decode.id); - if (!user) + if (!user) { return res.status(500).json({ success: false, - message: "invalid user ! try to login again", + message: "Invalid user! Try to login again", + }); + } req.user = user; + next(); } catch (err) { - //verification - issue - console.log(err); return res.status(401).json({ success: false, - message: "token is invalid", + message: "Token is invalid", }); } - next(); } catch (error) { return res.status(401).json({ success: false, - message: `Something went wrong while validating the token ${error.message}`, + message: `Something went wrong while validating the token: ${error.message}`, }); } }; -//isCanteen(canteen manager) account type +// isCanteen middleware exports.isCanteen = async (req, res, next) => { try { - console.log("isCanteen middleware", req.user); if (req.user.accountType !== "Canteen") { return res.status(401).json({ success: false, diff --git a/src/components/ModalForm.jsx b/src/components/ModalForm.jsx index d8f9339..09ae7d4 100644 --- a/src/components/ModalForm.jsx +++ b/src/components/ModalForm.jsx @@ -60,7 +60,7 @@ const ModalForm = ({ onSubmit , sectionName , canteenData , id}) => { if(sectionName === "Breakfast"){ - const apiUrl = `${process.env.REACT_APP_BASE_URL}/${id}/breakfast/add`; + const apiUrl = `http://localhost:8000/api/v1/${id}/breakfast/add`; axios.post(apiUrl , foodDetails) .then((response)=>{ @@ -75,7 +75,7 @@ const ModalForm = ({ onSubmit , sectionName , canteenData , id}) => { } else if(sectionName === "Lunch"){ - const apiUrl = `${process.env.REACT_APP_BASE_URL}/${id}/lunch/add`; + const apiUrl = `http://localhost:8000/api/v1/${id}/lunch/add`; axios.post(apiUrl , foodDetails) .then((response)=>{ @@ -92,7 +92,7 @@ const ModalForm = ({ onSubmit , sectionName , canteenData , id}) => { } else{ - const apiUrl = `${process.env.REACT_APP_BASE_URL}/${id}/dinner/add`; + const apiUrl = `http://localhost:8000/api/v1/${id}/dinner/add`; axios.post(apiUrl , foodDetails) .then((response)=>{ diff --git a/src/pages/AddFoodItem.jsx b/src/pages/AddFoodItem.jsx new file mode 100644 index 0000000..476c6ab --- /dev/null +++ b/src/pages/AddFoodItem.jsx @@ -0,0 +1,143 @@ +import React, { useState, useEffect } from "react"; +import axios from "axios"; +import { toast } from "react-hot-toast"; + +function AddFoodItem() { + const [formData, setFormData] = useState({ + dish: "", + dishId: "", + mealType: "", + }); + + const [loading, setLoading] = useState(false); + + useEffect(() => { + const canteenId = localStorage.getItem("canteenId"); + if (!canteenId) { + toast.error("Canteen ID is missing. Please log in again."); + } + }, []); + + const handleChange = (event) => { + setFormData({ + ...formData, + [event.target.name]: event.target.value, + }); + }; + + const handleSubmit = async (event) => { + event.preventDefault(); + setLoading(true); + + const { mealType, dish, dishId } = formData; + const canteenId = localStorage.getItem("canteenId"); + let apiUrl = ""; + + switch (mealType) { + case "Breakfast": + apiUrl = `http://localhost:8000/api/v1/${canteenId}/breakfast/add`; + break; + case "Lunch": + apiUrl = `http://localhost:8000/api/v1/${canteenId}/lunch/add`; + break; + case "Dinner": + apiUrl = `http://localhost:8000/api/v1/${canteenId}/dinner/add`; + break; + default: + toast.error("Please select a meal type."); + setLoading(false); + return; + } + + // Get token from local storage or cookies + const token = localStorage.getItem("token"); // or use cookies + + if (!token) { + toast.error("Token is missing. Please log in again."); + setLoading(false); + return; + } + + try { + await axios.post( + apiUrl, + { dish, dishId }, + { + headers: { + Authorization: `Bearer ${token}`, + }, + } + ); + toast.success("Dish added successfully!"); + setFormData({ + dish: "", + dishId: "", + mealType: "", + }); + } catch (error) { + toast.error("Failed to add dish. Please try again."); + console.error(error); + } finally { + setLoading(false); + } + }; + + return ( +
- Connecting You to Your College - Canteens + Connecting You to Your College Canteens