User Below is my models/user: import mongoose, { Schema, models } from "mongoose" const…
- User
User Below is my models/user: import mongoose, { Schema, models } from "mongoose"
const userSchema = new Schema ( { name: { type: String, required: true, }, email: { type: String, required: true, }, password: { type: String, required: true, }, dob: { type: Date, required: true, }, constituency: { type: String, required: true, }, uvc: { type: String }, voted: { type: Boolean, required: true, }, admin: { type: Boolean, required: true, } }, { timestamps: true } );
const User = models.User || mongoose.model("User", userSchema); export default User;
Below is my partyselection.jsx: "use client";
import React, { useEffect, useState } from 'react'; import axios from 'axios'; import { useRouter } from 'next/navigation'; // Import useRouter
export default function Dashboard() { const [showPopup, setShowPopup] = useState(false); const [selectedParty, setSelectedParty] = useState(''); const [parties, setParties] = useState({}); // Updated
const router = useRouter(); // Create an instance of useRouter const handleLogout = async () => { try { await axios.post('/api/logout'); router.push('/'); // Redirect to home page } catch (error) { console.error('Error during logout:', error); } }; useEffect(() => { const fetchParties = async () => { try { const response = await axios.get('api/partymembers'); setParties(response.data); // Update parties with response data } catch (error) { console.error('Error fetching parties:', error); } }; fetchParties(); }, []); const partyColors = { Blue: 'bg-blue-500', Red: 'bg-red-500', Yellow: 'bg-yellow-500', Independent: 'bg-gray-500', }; const handlePartySelect = (party) => { setSelectedParty(party); setShowPopup(true); }; const handleClosePopup = () => { setShowPopup(false); setSelectedParty(''); }; // Modify handleSubmit in PartySelection.jsx const handleSubmit = async (event) => { event.preventDefault(); const candidateName = event.target.candidate.value; try { // First, check if the user has already voted const voteCheckResponse = await axios.get('/api/checkvoted'); // Check if the user has already voted if (voteCheckResponse.status === 403) { alert("You have already cast your vote."); return; // Exit the function to prevent further execution } // If the user hasn't voted, continue with the voting process const voteResponse = await axios.post('/api/incrementvote', { candidateName, party: selectedParty }); if (voteResponse.status === 200) { alert(`Vote for ${candidateName} from ${selectedParty} Party submitted successfully!`); handleClosePopup(); } else { throw new Error("Failed to submit the vote"); } } catch (error) { if (error.response && error.response.status === 403) { // Handle the specific case where the user has already voted alert("You have already cast your vote."); } else { // Handle other errors console.error('Error submitting vote:', error); alert('Error submitting vote. Please try again.'); } } }; return ( <div className="grid place-items-center min-h-screen"> {/* Logout Button */} <div className="absolute top-4 right-4"> <button onClick={handleLogout} className="bg-red-600 text-white font-bold cursor-pointer px-6 py-2 rounded" > Log Out </button> </div> {/* Rest of the Dashboard */} <div className="grid grid-cols-1 md:grid-cols-2 gap-6 p-4 w-full max-w-4xl"> {/* ... */} </div> <div className="grid grid-cols-1 md:grid-cols-2 gap-6 p-4 w-full max-w-4xl"> {/* Party buttons */} {Object.keys(parties).map((party, index) => ( <div key={index} className="shadow-lg p-8 bg-zinc-300/10 flex flex-col gap-4"> <div className="text-center"> <span className="font-bold text-lg md:text-xl">{`${party} Party`}</span> </div> <button className={`${partyColors[party]} text-white font-bold px-4 py-2 text-sm md:text-lg w-full`} onClick={() => handlePartySelect(party)} > View candidates </button> </div> ))} {/* Popup */} {showPopup && ( <div className="fixed top-0 left-0 w-full h-full bg-black bg-opacity-50 flex justify-center items-center"> <div className="bg-white p-5 rounded flex flex-col items-center justify-center"> <form onSubmit={handleSubmit} className="w-full"> <label className="block text-center mb-4">Select a candidate from {selectedParty} Party:</label> <select name="candidate" className="w-full p-2 border border-gray-300 rounded mb-4"> {parties[selectedParty].map((candidate, index) => ( <option key={index} value={candidate}>{candidate}</option> ))} </select> <div className="flex justify-between gap-3"> <button type="submit" className="bg-green-500 text-white px-4 py-2 rounded flex-1">Submit</button> <button type="button" onClick={handleClosePopup} className="bg-orange-500 text-white px-4 py-2 rounded flex-1">Cancel</button> </div> </form> </div> </div> )} </div> </div> ); - Assistant
- User
My checkvoted api shown below gets the users via their email, which is stored in cookies. Please apply this to logic to fix the api you have provided: import { connectMongoDB } from "@/lib/mongodb"; import User from "@/models/user"; import { NextResponse } from "next/server";
export async function GET(req) { try { await connectMongoDB();
// Retrieve the user's email from the cookie const email = req.cookies.get('email').value; // Assuming email is stored in a cookie console.log(email) if (!email) { return new Response( JSON.stringify({ message: "No user email found in cookies" }), { status: 401, headers: { 'Content-Type': 'application/json' } } ); } // Find the user by email const user = await User.findOne({ email }); if (!user) { return new Response( JSON.stringify({ message: "User not found" }), { status: 404, headers: { 'Content-Type': 'application/json' } } ); } // Check if the user has already voted if (user.voted) { return new Response( JSON.stringify({ message: "User has already voted" }), { status: 403, headers: { 'Content-Type': 'application/json' } } ); } // User has not voted return new Response( JSON.stringify({ message: "User has not voted" }), { status: 200, headers: { 'Content-Type': 'application/json' } } ); } catch (error) { console.error("Error checking voting status: ", error); return new Response( JSON.stringify({ message: "An error occurred while checking voting status", error: error.message }), { status: 500, headers: { 'Content-Type': 'application/json' } } ); } - Assistant
- User
My voting is handled in the jsx file. Please review.
- Assistant
- User
My program already increments the vote. Please provide the api that will take the email from cookies like in the prior example, and set the users voted value in the database to true.
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.