Skip to content

Commit

Permalink
Merge pull request #251 from nishant0708/working-add-menuitem
Browse files Browse the repository at this point in the history
Feat:Want To Add Backend Canteen menu item #232
  • Loading branch information
hustlerZzZ authored Jun 7, 2024
2 parents ea11511 + 3d9b4ad commit db7f1f2
Show file tree
Hide file tree
Showing 9 changed files with 264 additions and 169 deletions.
19 changes: 14 additions & 5 deletions server/controllers/Auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -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",
});
}

Expand All @@ -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",
Expand All @@ -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;
Expand Down
80 changes: 39 additions & 41 deletions server/middlewares/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
6 changes: 3 additions & 3 deletions src/components/ModalForm.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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)=>{
Expand All @@ -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)=>{
Expand All @@ -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)=>{
Expand Down
143 changes: 143 additions & 0 deletions src/pages/AddFoodItem.jsx
Original file line number Diff line number Diff line change
@@ -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 (
<div className="flex justify-center items-center h-screen bg-gray-100">
<form
onSubmit={handleSubmit}
className="bg-white p-6 rounded shadow-lg w-full max-w-sm"
>
<h1 className="text-xl font-bold mb-4">Add Food Item</h1>
<div className="mb-4">
<label className="block text-gray-700">Dish Name</label>
<input
type="text"
name="dish"
value={formData.dish}
onChange={handleChange}
className="w-full p-2 border border-gray-300 rounded mt-1"
required
/>
</div>
<div className="mb-4">
<label className="block text-gray-700">Dish ID</label>
<input
type="text"
name="dishId"
value={formData.dishId}
onChange={handleChange}
className="w-full p-2 border border-gray-300 rounded mt-1"
required
/>
</div>
<div className="mb-4">
<label className="block text-gray-700">Meal Type</label>
<select
name="mealType"
value={formData.mealType}
onChange={handleChange}
className="w-full p-2 border border-gray-300 rounded mt-1"
required
>
<option value="" disabled hidden>
Select Meal Type
</option>
<option value="Breakfast">Breakfast</option>
<option value="Lunch">Lunch</option>
<option value="Dinner">Dinner</option>
</select>
</div>
<button
type="submit"
className="w-full bg-blue-500 text-white p-2 rounded mt-4"
disabled={loading}
>
{loading ? "Loading..." : "Add Dish"}
</button>
</form>
</div>
);
}

export default AddFoodItem;
2 changes: 1 addition & 1 deletion src/pages/Home.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 :{
Expand Down
Loading

0 comments on commit db7f1f2

Please sign in to comment.