diff --git a/client/src/pages/CarbonCredits/Bids.js b/client/src/pages/CarbonCredits/Bids.js index 9788b1b..5d2a524 100644 --- a/client/src/pages/CarbonCredits/Bids.js +++ b/client/src/pages/CarbonCredits/Bids.js @@ -27,8 +27,6 @@ function Bids({ showBidsModal, setShowBidsModal, selectedSellCredit }) { if (response.ok) { const data = await response.json(); console.log("dataaa", data); - message.success("🪙5 Credits are rewarded! 🎊"); - setBidsData(data.data); } } catch (error) { diff --git a/client/src/pages/CarbonCredits/CCredits.js b/client/src/pages/CarbonCredits/CCredits.js index e608eb7..68598d6 100644 --- a/client/src/pages/CarbonCredits/CCredits.js +++ b/client/src/pages/CarbonCredits/CCredits.js @@ -16,7 +16,7 @@ function Carbon_Credits() { const fetchCredits = async () => { try { setLoading(true); - dispatch(SetLoader(true)) + dispatch(SetLoader(true)); const token = localStorage.getItem("usersdatatoken"); const creditsResponse = await fetch("/get-credits/user", { method: "GET", @@ -38,8 +38,15 @@ function Carbon_Credits() { }); setCredits(updatedCredits); - const activeApprovedCredits = updatedCredits.filter(credit => credit.status === "Active"); - setTotalCredits(activeApprovedCredits.reduce((total, credit) => total + credit.amount, 0)); + const activeApprovedCredits = updatedCredits.filter( + (credit) => credit.status === "Active" + ); + setTotalCredits( + activeApprovedCredits.reduce( + (total, credit) => total + credit.amount, + 0 + ) + ); const rewardCreditsResponse = await fetch("/get-reward-credits-user", { method: "GET", @@ -65,7 +72,7 @@ function Carbon_Credits() { useEffect(() => { fetchCredits(); - + updateCredits(); const interval = setInterval(fetchCredits, 60000); return () => clearInterval(interval); @@ -73,7 +80,9 @@ function Carbon_Credits() { const updateCredits = async () => { try { - const expiredCredits = credits.filter((credit) => credit.status === "Expired"); + const expiredCredits = credits.filter( + (credit) => credit.status === "Expired" + ); if (expiredCredits.length > 0) { const token = localStorage.getItem("usersdatatoken"); @@ -89,7 +98,7 @@ function Carbon_Credits() { }); if (response.ok) { - console.log("Credits status updated in the database"); + console.log("Credits status updated"); } else { throw new Error("Failed to update credits status in the database"); } @@ -123,7 +132,17 @@ function Carbon_Credits() { title: "Project Name", dataIndex: "projectName", key: "projectName", - render: (text) => {text} + render: (text) => ( + + {text} + + ), }, { title: "Credit Amount", @@ -134,7 +153,18 @@ function Carbon_Credits() { title: "Status", dataIndex: "status", key: "status", - render: (text, record) => {text} + render: (text, record) => ( + + {text} + + ), }, { title: "Remaining Time", @@ -142,7 +172,11 @@ function Carbon_Credits() { key: "expiryDate", render: (expiryDate, record) => { const { status, remainingTime } = calculateTimeLeft(expiryDate); - return status === "Active" ? : {record.status}; + return status === "Active" ? ( + + ) : ( + {record.status} + ); }, }, ]; diff --git a/client/src/pages/CarbonCredits/Credits.js b/client/src/pages/CarbonCredits/Credits.js index 8c54e58..e3c6bff 100644 --- a/client/src/pages/CarbonCredits/Credits.js +++ b/client/src/pages/CarbonCredits/Credits.js @@ -53,7 +53,6 @@ function Credits() { const data = await res.json(); console.log(data); message.success(data.message); - message.success("🪙5 Credits are rewarded! 🎊") getData(); } else { console.error("Error deleting form"); diff --git a/client/src/pages/CarbonCredits/CreditsForm.js b/client/src/pages/CarbonCredits/CreditsForm.js index 836c22b..b94a383 100644 --- a/client/src/pages/CarbonCredits/CreditsForm.js +++ b/client/src/pages/CarbonCredits/CreditsForm.js @@ -136,7 +136,6 @@ const CreditsForm = ({ setShowCreditsForm, selectedCredit, getData, editMode, ha const data = await res.json(); //console.log(data); message.success(data.message); - message.success("🪙5 Credits are rewarded! 🎊") getData(); // Update the data after successful edit setShowCreditsForm(false); }else{ @@ -163,7 +162,7 @@ const CreditsForm = ({ setShowCreditsForm, selectedCredit, getData, editMode, ha baselineEmissionAmount: "", numOfTrees: "", numOfSolarPanels: "", electricity: "", status: "", images: []}); await getData(); message.success(data.message); - message.success("🪙50 Credits are rewarded! 🎊") + message.success("🪙50 points are rewarded! 🎊") setShowCreditsForm(false); } else { message.error('Error submitting the form. Please try again.'); diff --git a/client/src/pages/CarbonCredits/SellCreditsForm.js b/client/src/pages/CarbonCredits/SellCreditsForm.js index 9fe78c6..1c3ea3a 100644 --- a/client/src/pages/CarbonCredits/SellCreditsForm.js +++ b/client/src/pages/CarbonCredits/SellCreditsForm.js @@ -120,7 +120,7 @@ const SellCreditsForm = ({ }); await getData(); message.success(data.message); - message.success("🪙25 Credits are rewarded! 🎊") + message.success("🪙25 Points are rewarded! 🎊") setShowSellCreditsForm(false); } else { message.error("Error submitting the form. Please try again."); diff --git a/client/src/pages/Dashboard.js b/client/src/pages/Dashboard.js index b267cd7..922934e 100644 --- a/client/src/pages/Dashboard.js +++ b/client/src/pages/Dashboard.js @@ -54,10 +54,10 @@ const Dashboard = () => { Authorization: token, }, }); - if(resnotify.ok){ + if (resnotify.ok) { const responseData = await resnotify.json(); setNotifications(responseData.data); - }else{ + } else { throw new Error(resnotify.message); } } catch (error) { @@ -109,7 +109,6 @@ const Dashboard = () => { localStorage.removeItem("usersdatatoken"); setLoginData(false); message.success("Logged out Successfully"); - message.success("🪙 1 Credit rewarded! 🎊"); navigate("/login"); } }; diff --git a/client/src/pages/Login.js b/client/src/pages/Login.js index ade4a75..4209d8e 100644 --- a/client/src/pages/Login.js +++ b/client/src/pages/Login.js @@ -1,104 +1,122 @@ -import React, {useState} from 'react' -import { NavLink } from 'react-router-dom'; -import { useNavigate } from 'react-router-dom'; -import "./mix.css" -import { useDispatch } from 'react-redux'; -import { SetLoader } from '../redux/loadersSlice'; -import { message } from 'antd'; +import React, { useState } from "react"; +import { NavLink } from "react-router-dom"; +import { useNavigate } from "react-router-dom"; +import "./mix.css"; +import { useDispatch } from "react-redux"; +import { SetLoader } from "../redux/loadersSlice"; +import { message } from "antd"; + const Login = () => { + const [passShow, setPassShow] = useState(false); - const [passShow, setPassShow] = useState(false); - - const [inpval, setInpval] = useState({ - email:"", - password:"" + const [inpval, setInpval] = useState({ + email: "", + password: "", + }); + const navigate = useNavigate(); + const dispatch = useDispatch(); + const setVal = (e) => { + const { name, value } = e.target; + setInpval(() => { + return { + ...inpval, + [name]: value, + }; }); - const navigate = useNavigate(); - const dispatch = useDispatch(); - const setVal = (e) =>{ - - const {name, value} = e.target; - setInpval(()=>{ - return{ - ...inpval, - [name]:value - } + }; + + const loginuser = async (e) => { + e.preventDefault(); + const { email, password } = inpval; + + if (email === "") { + message.error("Please enter your email"); + } else if (!email.includes("@gmail.com")) { + message.error("Please enter a valid email"); + } else if (password === "") { + message.error("Enter your password"); + } else if (password.length < 6) { + message.error("Password must be at least 6 characters"); + } else { + dispatch(SetLoader(true)); + try { + const data = await fetch("/login", { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ email, password }), }); - }; - - - const loginuser = async (e) => { - e.preventDefault(); - const { email, password } = inpval; - - if (email === "") { - message.error("Please enter your email"); - } else if (!email.includes("@gmail.com")) { - message.error("Please enter a valid email"); - } else if (password === "") { - message.error("Enter your password"); - } else if (password.length < 6) { - message.error("Password must be at least 6 characters"); + const res = await data.json(); + dispatch(SetLoader(false)); + console.log(res); + if (res.status === 201) { + localStorage.setItem("usersdatatoken", res.result.token); + message.success("Welcome to CARBON CREDIT MARKETPLACE"); + navigate("/home"); + setInpval({ ...inpval, email: "", password: "" }); + } else if (res.error === "User account is blocked") { + message.error("Your account is blocked!!!"); } else { - dispatch(SetLoader(true)); - try { - const data = await fetch("/login", { - method: "POST", - headers: { - "Content-Type": "application/json" - }, - body: JSON.stringify({ email, password }) - }); - const res = await data.json(); - dispatch(SetLoader(false)); - console.log(res); - if (res.status === 201) { - localStorage.setItem("usersdatatoken", res.result.token); - message.success("Welcome to CARBON CREDIT MARKETPLACE"); - message.success("🪙 2 Credits are rewarded! 🎊") - navigate("/home"); - setInpval({ ...inpval, email: "", password: "" }); - } else if (res.error === "User account is blocked") { - message.error("Your account is blocked!!!"); - } else { - message.error("Invalid Details"); - } - } catch (error) { - dispatch(SetLoader(false)); - message.error("An error occurred. Please try again later."); - console.error("Login error:", error); - } + message.error("Invalid Details"); } - }; - - return ( + } catch (error) { + dispatch(SetLoader(false)); + message.error("An error occurred. Please try again later."); + console.error("Login error:", error); + } + } + }; + + return ( <> -
-
-
-

Welcome Back, Log In

+
+
+
+

Welcome Back, Log In

+
+
+
+ + +
+
+ +
+ +
setPassShow(!passShow)} + > + {!passShow ? "Show" : "Hide"}
- -
- - -
-
- -
- -
setPassShow(!passShow)}> - {!passShow ? "Show" : "Hide"} -
-
-
- -

Don't have an Account? Sign Up

- +
-
+ +

+ Don't have an Account? Sign Up +

+ +
+
- ) -} + ); +}; -export default Login \ No newline at end of file +export default Login; diff --git a/client/src/pages/Profile.js b/client/src/pages/Profile.js index 95eec1e..052377d 100644 --- a/client/src/pages/Profile.js +++ b/client/src/pages/Profile.js @@ -1,13 +1,13 @@ -import * as React from 'react'; -import PropTypes from 'prop-types'; -import Tabs from '@mui/material/Tabs'; -import Tab from '@mui/material/Tab'; -import Typography from '@mui/material/Typography'; -import Box from '@mui/material/Box'; -import { ThemeProvider, createTheme } from '@mui/material/styles'; -import Credits from './CarbonCredits/Credits'; -import Carbon_Credits from './CarbonCredits/CCredits'; -import SellCredits from './CarbonCredits/SellCredits'; +import * as React from "react"; +import PropTypes from "prop-types"; +import Tabs from "@mui/material/Tabs"; +import Tab from "@mui/material/Tab"; +import Typography from "@mui/material/Typography"; +import Box from "@mui/material/Box"; +import { ThemeProvider, createTheme } from "@mui/material/styles"; +import Credits from "./CarbonCredits/Credits"; +import Carbon_Credits from "./CarbonCredits/CCredits"; +import SellCredits from "./CarbonCredits/SellCredits"; function CustomTabPanel(props) { const { children, value, index, ...other } = props; @@ -38,7 +38,7 @@ CustomTabPanel.propTypes = { function a11yProps(index) { return { id: `simple-tab-${index}`, - 'aria-controls': `simple-tabpanel-${index}`, + "aria-controls": `simple-tabpanel-${index}`, }; } @@ -47,22 +47,21 @@ const theme = createTheme(); const StyledTab = (props) => ( ); - export default function Profile() { const [value, setValue] = React.useState(0); const [rewardCredits, setRewardCredits] = React.useState(0); - + const fetchRewardCredits = async () => { - try{ + try { const token = localStorage.getItem("usersdatatoken"); const res = await fetch("/get-reward-credits-user", { method: "GET", @@ -73,12 +72,12 @@ export default function Profile() { }); const data = await res.json(); setRewardCredits(data.reward_credits); - }catch(error){ + } catch (error) { console.log(error.message); } }; - React.useEffect(()=> { + React.useEffect(() => { // fetching rewardcredits fetchRewardCredits(); }, []); @@ -89,26 +88,43 @@ export default function Profile() { return ( - - + + - - - - + + + + {/* Content for Carbon Credits tab */} - < Credits /> + - < Carbon_Credits /> + diff --git a/client/src/pages/Register.js b/client/src/pages/Register.js index 7c9a9cb..c98e12e 100644 --- a/client/src/pages/Register.js +++ b/client/src/pages/Register.js @@ -1,125 +1,170 @@ -import React, {useState} from 'react' -import { NavLink, useNavigate } from 'react-router-dom'; -import { useDispatch } from 'react-redux'; -import { SetLoader } from '../redux/loadersSlice'; -import { message } from 'antd'; +import React, { useState } from "react"; +import { NavLink, useNavigate } from "react-router-dom"; +import { useDispatch } from "react-redux"; +import { SetLoader } from "../redux/loadersSlice"; +import { message } from "antd"; // import {ToastContainer, toast} from 'react-toastify'; // import 'react-toastify/dist/ReactToastify.css'; import "./mix.css"; const Register = () => { + const [passShow, setPassShow] = useState(false); + const [cpassShow, setcPassShow] = useState(false); + const navigate = useNavigate(); + const dispatch = useDispatch(); + const [inpval, setInpval] = useState({ + fname: "", + email: "", + password: "", + cpassword: "", + }); - const [passShow, setPassShow] = useState(false); - const [cpassShow, setcPassShow] = useState(false); - const navigate = useNavigate(); - const dispatch = useDispatch(); - const [inpval, setInpval] = useState({ - fname:"", - email:"", - password:"", - cpassword:"" + const setVal = (e) => { + //console.log(e.target.value); + const { name, value } = e.target; + setInpval(() => { + return { + ...inpval, + [name]: value, + }; }); - - const setVal = (e) =>{ - //console.log(e.target.value); - const {name, value} = e.target; - setInpval(()=>{ - return{ - ...inpval, - [name]:value - } - }); - }; - - const addUserdata = async (e) =>{ - e.preventDefault(); + }; - const {fname, email, password, cpassword} = inpval; + const addUserdata = async (e) => { + e.preventDefault(); - if(fname === ""){ - message.error("Username is required"); - }else if(email === ""){ - message.error("Email is required"); - }else if(!email.includes("@gmail.com")){ - message.error("Please enter valid email"); - }else if(password === ""){ - message.error("Enter your Password"); - }else if(password.length < 6){ - message.error("Password must be 6 char"); - }else if(cpassword === ""){ - message.error("Enter your confirm password"); - }else if(cpassword.length < 6){ - message.error("Confirm Password must be 6 char"); - }else if(password !== cpassword){ - message.error("Password and Confirm Password must be same"); - }else{ - dispatch(SetLoader(true)); - // console.log("user registration done"); - const data = await fetch("/register",{ - method: "POST", - headers:{ - "Content-Type":"application/json" - }, - body: JSON.stringify({ - fname, email, password, cpassword - }) - }); - const res = await data.json(); - dispatch(SetLoader(false)); - //console.log(res); - if(res.status === 201){ - message.success("Congratulations!!! 🎉 You are registered"); - message.success("Please Login with your credentials"); - message.success("🪙 10 Credits are rewarded! 🎊") - setInpval({...inpval, fname:"", email:"", password:"", cpassword:""}); - navigate("/login"); - } - } + const { fname, email, password, cpassword } = inpval; + if (fname === "") { + message.error("Username is required"); + } else if (email === "") { + message.error("Email is required"); + } else if (!email.includes("@gmail.com")) { + message.error("Please enter valid email"); + } else if (password === "") { + message.error("Enter your Password"); + } else if (password.length < 6) { + message.error("Password must be 6 char"); + } else if (cpassword === "") { + message.error("Enter your confirm password"); + } else if (cpassword.length < 6) { + message.error("Confirm Password must be 6 char"); + } else if (password !== cpassword) { + message.error("Password and Confirm Password must be same"); + } else { + dispatch(SetLoader(true)); + // console.log("user registration done"); + const data = await fetch("/register", { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + fname, + email, + password, + cpassword, + }), + }); + const res = await data.json(); + dispatch(SetLoader(false)); + //console.log(res); + if (res.status === 201) { + message.success("Congratulations!!! 🎉 You are registered"); + message.success("Please Login with your credentials"); + message.success("🪙 10 points are rewarded! 🎊"); + setInpval({ + ...inpval, + fname: "", + email: "", + password: "", + cpassword: "", + }); + navigate("/login"); + } } + }; - return ( + return ( <> -
-
-
-

Sign Up

+
+
+
+

Sign Up

+
+
+
+ + +
+
+ + +
+
+ +
+ +
setPassShow(!passShow)} + > + {!passShow ? "Show" : "Hide"} +
+
+
+
+ +
+ +
setcPassShow(!cpassShow)} + > + {!cpassShow ? "Show" : "Hide"}
- -
- - -
-
- - -
-
- -
- -
setPassShow(!passShow)}> - {!passShow ? "Show" : "Hide"} -
-
-
-
- -
- -
setcPassShow(!cpassShow)}> - {!cpassShow ? "Show" : "Hide"} -
-
-
- -

Already have an Account? Login

- +
-
+ +

+ Already have an Account? Login +

+ +
+
- ) -} + ); +}; -export default Register \ No newline at end of file +export default Register; diff --git a/client/src/pages/SellCreditsInfo/BidModel.js b/client/src/pages/SellCreditsInfo/BidModel.js index 81ee6ff..62f919e 100644 --- a/client/src/pages/SellCreditsInfo/BidModel.js +++ b/client/src/pages/SellCreditsInfo/BidModel.js @@ -34,12 +34,12 @@ function BidModel({ showBidModal, setShowBidModal, sellCredit, reloadData }) { if (response.ok) { message.success("Bid added successfully"); - message.success("🪙5 Credits are rewarded! 🎊"); + message.success("🪙5 points are rewarded! 🎊"); // send notification to seller const notifyUser = { title: "A new bid has been placed", - message: `A new bid has been placed on your carbon credits 🪙${sellCredit?.data?.sellCredits} for 🫰🏻 ₹ ${formDataWithUser?.bidAmount}`, + message: `A new bid has been placed on your carbon credits ${sellCredit?.data?.sellCredits} for 🫰🏻 ₹ ${formDataWithUser?.bidAmount}`, user: sellCredit?.data?.user?._id, onClick: `/profile`, read: false, diff --git a/server/routes/bidsRoute.js b/server/routes/bidsRoute.js index 3df0997..443c37e 100644 --- a/server/routes/bidsRoute.js +++ b/server/routes/bidsRoute.js @@ -2,9 +2,7 @@ const express = require("express"); const router = new express.Router(); const Bid = require("../models/bid"); const authenticate = require("../middleware/authenticate"); -const morgan = require("morgan"); -router.use(morgan("combined")); // place a new bid router.post("/place-new-bid", authenticate, async (req, res) => { const user = req.rootUser; // Assuming you have a valid user object in req.rootUser @@ -25,9 +23,6 @@ router.post("/place-new-bid", authenticate, async (req, res) => { // get all bids router.post("/get-all-bids-for-all-users", authenticate, async (req, res) => { - const user = req.rootUser; - user.rewardCredits += 5; - await user.save(); try { const { selectedSellCredit} = req.body; console.log("sss", selectedSellCredit); @@ -50,8 +45,6 @@ router.post("/get-all-bids-for-all-users", authenticate, async (req, res) => { router.post("/get-particular-all-bids", authenticate, async (req, res) => { const user = req.rootUser; - user.rewardCredits += 5; - await user.save(); try { const { selectedSellCredit} = req.body; console.log("sss", selectedSellCredit); diff --git a/server/routes/creditsFormRoute.js b/server/routes/creditsFormRoute.js index ba58a8f..25cb577 100644 --- a/server/routes/creditsFormRoute.js +++ b/server/routes/creditsFormRoute.js @@ -60,8 +60,6 @@ router.get("/get-credit-forms", async (req, res) => { // edit form router.put("/edit-credit-forms/:id", authenticate, async (req, res) => { - const user = req.rootUser; - try { const { id } = req.params; if (!ObjectId.isValid(id)) { @@ -89,9 +87,6 @@ router.put("/edit-credit-forms/:id", authenticate, async (req, res) => { // delete the form router.delete("/delete-credit-forms/:id", authenticate, async (req, res) => { - const user = req.rootUser; - user.rewardCredits += 5; - await user.save(); try { await CreditForm.findByIdAndDelete(req.params.id); res.send({ diff --git a/server/routes/userRoute.js b/server/routes/userRoute.js index f77b9b8..e58f748 100644 --- a/server/routes/userRoute.js +++ b/server/routes/userRoute.js @@ -3,144 +3,144 @@ const router = new express.Router(); const userdb = require("../models/user"); const bcrypt = require("bcryptjs"); const authenticate = require("../middleware/authenticate"); -const morgan = require("morgan"); -const analyzeAccessLogs = require("../middleware/analyzeAccessLogs"); -router.use(morgan("combined")); // for user registration -router.post("/register", async(req, res) =>{ - const {fname, email, password, cpassword} = req.body; - if(!fname || !email || !password || !cpassword){ - res.status(422).json({error: "fill all the details"}) +router.post("/register", async (req, res) => { + const { fname, email, password, cpassword } = req.body; + if (!fname || !email || !password || !cpassword) { + res.status(422).json({ error: "fill all the details" }); + } + try { + // check if user exists + const preuser = await userdb.findOne({ email: email }); + if (preuser) { + res.status(422).json({ error: "This Email is Already Exist" }); + } else if (password !== cpassword) { + res + .status(422) + .json({ error: "Password and Confirm Password not match" }); + } else { + // creating new user + const finalUser = new userdb({ + fname, + email, + password, + cpassword, + }); + + // 10 points as reward upon registering + finalUser.rewardCredits = 10; + + const storeData = await finalUser.save(); + //console.log(storeData); + res.status(201).json({ status: 201, storeData }); } - try{ - // check if user exists - const preuser = await userdb.findOne({email: email}); - if(preuser){ - res.status(422).json({error: 'This Email is Already Exist'}); - }else if(password !== cpassword){ - res.status(422).json({error: "Password and Confirm Password not match"}); - }else{ - // creating new user - const finalUser = new userdb({ - fname, email, password, cpassword - }); - - // 10 credits as reward upon registering - finalUser.rewardCredits = 10; - - const storeData = await finalUser.save(); - //console.log(storeData); - res.status(201).json({status:201, storeData}); - } - }catch(error){ - res.status(422).json(error); - console.log("catch error", error); - } + } catch (error) { + res.status(422).json(error); + console.log("catch error", error); + } }); router.post("/login", async (req, res) => { - const { email, password } = req.body; + const { email, password } = req.body; - if (!email || !password) { - return res.status(422).json({ error: "Fill in all the details" }); - } + if (!email || !password) { + return res.status(422).json({ error: "Fill in all the details" }); + } - try { - const userValid = await userdb.findOne({ email }); + try { + const userValid = await userdb.findOne({ email }); - if (!userValid) { - throw new Error("Invalid details"); - } + if (!userValid) { + throw new Error("Invalid details"); + } - if (userValid.status === "blocked") { - return res.status(422).json({ error: "User account is blocked" }); - } + if (userValid.status === "blocked") { + return res.status(422).json({ error: "User account is blocked" }); + } - const isMatch = await bcrypt.compare(password, userValid.password); + const isMatch = await bcrypt.compare(password, userValid.password); - if (!isMatch) { - return res.status(422).json({ error: "Invalid details" }); - } - - const token = await userValid.generateAuthtoken(); + if (!isMatch) { + return res.status(422).json({ error: "Invalid details" }); + } - res.cookie("usercookie", token, { - expires: new Date(Date.now() + 9000000), - httpOnly: true - }); + const token = await userValid.generateAuthtoken(); - const result = { - userValid, - token - }; + res.cookie("usercookie", token, { + expires: new Date(Date.now() + 9000000), + httpOnly: true, + }); - return res.status(201).json({ status: 201, result }); - } catch (error) { - console.error("Login error:", error); - return res.status(500).json({ error: "Internal server error" }); - } + const result = { + userValid, + token, + }; + + return res.status(201).json({ status: 201, result }); + } catch (error) { + console.error("Login error:", error); + return res.status(500).json({ error: "Internal server error" }); + } }); // user valid -router.get("/validuser", authenticate, async(req,res)=>{ - try { - const ValidUserOne = await userdb.findOne({_id:req.userId}); - res.status(201).json({status:201,ValidUserOne}); - } catch (error) { - res.status(401).json({status:401,error}); - } +router.get("/validuser", authenticate, async (req, res) => { + try { + const ValidUserOne = await userdb.findOne({ _id: req.userId }); + res.status(201).json({ status: 201, ValidUserOne }); + } catch (error) { + res.status(401).json({ status: 401, error }); + } }); // user logout -router.get("/logout", authenticate, async(req,res) =>{ - try { - req.rootUser.tokens = req.rootUser.tokens.filter((curelem)=>{ - return curelem.token !== req.token - }); - - res.clearCookie("usercookie",{path:"/"}); - - res.status(201).json({status:201}) - - } catch (error) { - res.status(401).json({status:401,error}) - } +router.get("/logout", authenticate, async (req, res) => { + try { + req.rootUser.tokens = req.rootUser.tokens.filter((curelem) => { + return curelem.token !== req.token; + }); + + res.clearCookie("usercookie", { path: "/" }); + + res.status(201).json({ status: 201 }); + } catch (error) { + res.status(401).json({ status: 401, error }); + } }); // get all users -router.get("/get-users", authenticate, async(req, res) => { - try{ - const users = await userdb.find(); - res.send({ - success: true, - message: "Users fetched successfully", - data: users, - }); - }catch(error){ - res.send({ - success: false, - message: error.message, - }); - } +router.get("/get-users", authenticate, async (req, res) => { + try { + const users = await userdb.find(); + res.send({ + success: true, + message: "Users fetched successfully", + data: users, + }); + } catch (error) { + res.send({ + success: false, + message: error.message, + }); + } }); // update user status -router.put("/update-user-status/:id", authenticate, async(req, res) => { - try{ - const { status } = req.body; - await userdb.findByIdAndUpdate(req.params.id, { status }); - res.send({ - success: true, - message: "User status updated successfully", - }) - }catch(error){ - res.send({ - success: false, - message: error.message, - }); - } +router.put("/update-user-status/:id", authenticate, async (req, res) => { + try { + const { status } = req.body; + await userdb.findByIdAndUpdate(req.params.id, { status }); + res.send({ + success: true, + message: "User status updated successfully", + }); + } catch (error) { + res.send({ + success: false, + message: error.message, + }); + } }); module.exports = router; -