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 ( +
+
+

Add Food Item

+
+ + +
+
+ + +
+
+ + +
+ +
+
+ ); +} + +export default AddFoodItem; diff --git a/src/pages/Home.jsx b/src/pages/Home.jsx index e58f3e6..0362fde 100644 --- a/src/pages/Home.jsx +++ b/src/pages/Home.jsx @@ -18,7 +18,7 @@ function Home() { try{ setLoading(true); const getCanteen = await fetch( - `${process.env.REACT_APP_BASE_URL}/getcanteen`, + `http://localhost:8000/api/v1/getcanteen`, { method : "GET", headers :{ diff --git a/src/pages/Login.jsx b/src/pages/Login.jsx index be1b9a2..5451cd7 100644 --- a/src/pages/Login.jsx +++ b/src/pages/Login.jsx @@ -1,15 +1,6 @@ -import React, { - useState, - useEffect, -} from "react"; -import { - AiOutlineEye, - AiOutlineEyeInvisible, -} from "react-icons/ai"; -import { - Link, - useNavigate, -} from "react-router-dom"; +import React, { useState } from "react"; +import { AiOutlineEye, AiOutlineEyeInvisible } from "react-icons/ai"; +import { Link, useNavigate } from "react-router-dom"; import { toast } from "react-hot-toast"; import axios from "axios"; import logo from "../assets/logo2.png"; @@ -23,7 +14,7 @@ function Login() { }); const [showPassword, setShowPassword] = useState(false); - const [loading, setLoading] = useState(false) + const [loading, setLoading] = useState(false); const navigate = useNavigate(); function changeHandler(event) { @@ -33,50 +24,35 @@ function Login() { })); } - async function submitHandler(event) { event.preventDefault(); + setLoading(true); - if (formData.accountType === "User") { - //Loader will show till the api fetching is done as show as promise is resolved the loader will be not shown - setLoading(true); + try { + const apiUrl = + formData.accountType === "User" + ? `http://localhost:8000/api/v1/studentLogin` + : `http://localhost:8000/api/v1/canteenLogin`; - // const apiUrl = `${process.env.REACT_APP_BASE_URL}/studentLogin`; - const apiUrl = `http://localhost:4000/api/v1/studentLogin`; + const response = await axios.post(apiUrl, formData); - try { - setLoading(true); - - const response = await axios.post(apiUrl, formData); + // Assuming the response contains a token + const token = response.data.token; - toast.success("Unable to login!"); + localStorage.setItem("token", token); + localStorage.setItem('canteenId', response.data.cantId); + if (formData.accountType === "User") { + toast.success("User logged in successfully!"); navigate("/home"); - } catch (error) { - toast.error("Failed To Login. Please try again."); - console.error(error); - } finally { - setLoading(false); + } else { + toast.success("Canteen logged in successfully!"); + navigate(`/section/${response.data.cantId}`); } - } - - else{ - const apiUrl = `${process.env.REACT_APP_BASE_URL}/canteenLogin`; - setLoading(true); - - axios - .post(apiUrl, formData) - .then((response) => { - setLoading(false); - toast.success("User Logged in "); - navigate( - `/section/${response.data.cantId}` - ); - }) - .catch((error) => { - //Loader will show till the api fetching is done as show as promise is resolved the loader will be not shown - setLoading(false); - toast.error("Failed to login"); - }); + } catch (error) { + toast.error("Failed to login. Please try again."); + console.error(error); + } finally { + setLoading(false); } } @@ -88,17 +64,11 @@ function Login() {
- logo + logo

- Connecting You to Your College - Canteens + Connecting You to Your College Canteens

-
@@ -108,13 +78,10 @@ function Login() {
-

- Hello Again! -

-

- Welcome Back -

+ onSubmit={submitHandler} + > +

Hello Again!

+

Welcome Back

- - - + +
@@ -155,11 +115,7 @@ function Login() { - setShowPassword( - (prev) => !prev - ) - }> - {showPassword ? ( - - ) : ( - - )} + onClick={() => setShowPassword((prev) => !prev)} + > + {showPassword ? : }
@@ -195,20 +144,9 @@ function Login() {
- - - - Don't have an account? Sign Up - - - - -
- - - + + )} + ); } diff --git a/src/pages/MenuPage.jsx b/src/pages/MenuPage.jsx index 252e8d9..bd5014f 100644 --- a/src/pages/MenuPage.jsx +++ b/src/pages/MenuPage.jsx @@ -20,7 +20,7 @@ function MenuPage() { try { setLoading(true); const getBreakfast = await fetch( - `${process.env.REACT_APP_BASE_URL}/${_id}/breakfast`, + `http://localhost:8000/api/v1/${_id}/breakfast`, { method: "GET", headers: { @@ -42,7 +42,7 @@ function MenuPage() { try { setLoading(true); const getLunch = await fetch( - `${process.env.REACT_APP_BASE_URL}/${_id}/lunch`, + `http://localhost:8000/api/v1/${_id}/lunch`, { method: "GET", headers: { @@ -64,7 +64,7 @@ function MenuPage() { try { setLoading(true); const getDinner = await fetch( - `${process.env.REACT_APP_BASE_URL}/${_id}/dinner`, + `http://localhost:8000/api/v1/${_id}/dinner`, { method: "GET", headers: { diff --git a/src/pages/SectionPage.jsx b/src/pages/SectionPage.jsx index 9e228d2..993a0db 100644 --- a/src/pages/SectionPage.jsx +++ b/src/pages/SectionPage.jsx @@ -5,6 +5,7 @@ import Modal from '../components/Modal'; import Navbar from '../components/Navbar'; import Loader from '../components/Loader/Loader'; import Footer from '../components/Footer'; +import AddFoodItem from './AddFoodItem'; const SectionPage = () => { const { _id } = useParams(); @@ -23,7 +24,7 @@ const SectionPage = () => { try { setLoading(true); const getCanteen = await fetch( - `${process.env.REACT_APP_BASE_URL}/getcanteen`, + `http://localhost:8000/api/v1/getcanteen`, { method: "GET", headers: { @@ -77,7 +78,7 @@ const SectionPage = () => { ) : ( <> -
+ {/*
@@ -88,7 +89,10 @@ const SectionPage = () => { Dinner
- + */} + + + ) } diff --git a/src/pages/Signup.jsx b/src/pages/Signup.jsx index e3695e0..3d62a48 100644 --- a/src/pages/Signup.jsx +++ b/src/pages/Signup.jsx @@ -98,7 +98,7 @@ function Signup() { lengthValidated ) { if (formData.accountType === "User") { - // const apiUrl = `${process.env.REACT_APP_BASE_URL}/studentSignup`; + // const apiUrl = `http://localhost:8000/api/v1/studentSignup`; const apiUrl = `http://localhost:8000/api/v1/studentSignup`; try { setLoading(true); @@ -115,14 +115,17 @@ function Signup() { } } else { const apiUrl = `http://localhost:8000/api/v1/canteenSignup` - // const apiUrl = `${process.env.REACT_APP_BASE_URL}/canteenSignup`; + // const apiUrl = `http://localhost:8000/api/v1/canteenSignup`; try { setLoading(true); const response = await axios.post(apiUrl, formData); - + const token = response.data.token; + + localStorage.setItem("token", token); + localStorage.setItem('canteenId', response.data.cantId); toast.success("Account Created Successfully!"); - navigate("/home"); + navigate(`/section/${response.data.cantId}`); } catch (error) { toast.error("Failed To Create Account. Please try again."); console.error(error);