Skip to content

Commit

Permalink
added poll stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
skushagra-rocketium committed Oct 5, 2024
1 parent 9e04fdd commit f36053d
Show file tree
Hide file tree
Showing 7 changed files with 87 additions and 15 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ api.http

# dependencies
node_modules
*/node_modules
/.pnp
.pnp.js

Expand Down
37 changes: 34 additions & 3 deletions client-admin/src/app/PollingApp/Vote.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,13 @@ import ScalerCampusBanner from "../../components/ScalerCampusBanner";
export default function Vote() {
let { pollId } = useParams();
const [pollData, setPollData] = useState({
question: "Who can be the next Miss Freshers?",
options: ["Option 1", "Option 2", "Option 3", "Option 4"],
question: "If you are seeing this question, possibilities are that :-",
options: [
"Something in our backend is broken",
"Your internet connection is weak",
"You do not have access",
"Some other crazy shit has happened.",
],
acceptingResponses: true,
});
const [selectedOption, setSelectedOption] = useState(null);
Expand All @@ -30,6 +35,29 @@ export default function Vote() {
fetchPollData();
}, [pollId]);

const handleVoteSubmit = async () => {
if (!selectedOption) {
alert("Please select a option");
return;
}

try {
const res = await axios
.post(`${process.env.REACT_APP_API_URL}/api/v1/poll/vote/${pollId}`, {
option: selectedOption,
user: localStorage.getItem("email"),
})
.then((res) => {
return res.data;
});
const data = await res.data;
} catch (error) {
const errorData = await error.response;
alert(errorData.data.message);
return;
}
};

const handleOptionClick = (option) => {
setSelectedOption(option);
console.log(`Selected option: ${option}`);
Expand Down Expand Up @@ -57,7 +85,10 @@ export default function Vote() {
{option}
</button>
))}
<button className="md:w-[50%] bg-[#1a1a1a] text-white h-[8vh] rounded-md font-semibold">
<button
onClick={handleVoteSubmit}
className="md:w-[50%] bg-[#1a1a1a] text-white h-[8vh] rounded-md font-semibold"
>
Submit Vote
</button>
</div>
Expand Down
3 changes: 2 additions & 1 deletion node-server-auth/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ PASSWORD_CHARSET=
JWT_SECRET=
JWT_EXPIRE=
DATABASE_URL=
MONGO_URI=
MONGO_URI=
MY_ORIGIN=
1 change: 1 addition & 0 deletions node-server-auth/src/app/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class App {
connectToDB();
this.app.use(cors());
this.app.use(express.json());
this.app.use(express.urlencoded({ extended: true }));
this.app.use(express.urlencoded({ extended: false }));

new RoutesRegister(this.app);
Expand Down
28 changes: 21 additions & 7 deletions node-server-auth/src/controllers/poll.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,14 @@ class PollController {
const { acceptingResponses } = req.body;
delete req.body.acceptingResponses;

const {options} = req.body;
const { options } = req.body;
if (!options) {
return res.status(400).json({ message: "Options are required" });
}

console.log('====================================');
console.log("====================================");
console.log(options);
console.log('====================================');
console.log("====================================");

const OptionT: OptionType = this.getOptionType(options);

Expand Down Expand Up @@ -72,9 +72,7 @@ class PollController {
const { pollId } = req.params;

if (!pollId) {
return res
.status(400)
.json({ message: "Poll ID is required" });
return res.status(400).json({ message: "Poll ID is required" });
}

try {
Expand All @@ -94,7 +92,7 @@ class PollController {
// TODO: validate user

console.log(poll.toObject().options);

console.log(poll.toObject().options[option]);

if (poll.toObject().options[option] == undefined) {
Expand All @@ -103,6 +101,22 @@ class PollController {
.json({ message: `Option "${option}" does not exist in this poll` });
}

const userVoted = poll.toObject().options[option].includes(user);
if (userVoted) {
return res.status(400).json({
message: `User "${user}" has already voted for "${option}"`,
});
}

// check with other options
for (let [key, value] of Object.entries(poll.toObject().options)) {
if (value.includes(user)) {
return res.status(400).json({
message: `User "${user}" has already voted for "${key}"`,
});
}
}

await PollModel.updateOne(
{ _id: pollId },
{
Expand Down
19 changes: 19 additions & 0 deletions node-server-auth/src/middlewares/checkOrigin.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Request, Response, NextFunction } from "express";

export default function checkOrigin(
req: Request,
res: Response,
next: NextFunction
) {
const origin = req.get("origin");

console.log("====================================");
console.log("origin", origin);
console.log("====================================");

if (origin === process.env.MY_ORIGIN) {
next();
} else {
return res.status(403).json({ message: "Access denied: Invalid origin" });
}
}
13 changes: 9 additions & 4 deletions node-server-auth/src/routes/poll.route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Router } from "express";
import PollController from "../controllers/poll.controller";
import checkOrigin from "../middlewares/checkOrigin.middleware";

class PollRoute {
public router: Router;
Expand All @@ -11,10 +12,14 @@ class PollRoute {
}

routes() {
this.router.get("", this.pollcontroller.getAllPolls);
this.router.post("", this.pollcontroller.createPoll);
this.router.post("/vote/:pollId", this.pollcontroller.voteOnPoll);
this.router.get("/:pollId", this.pollcontroller.getResults);
this.router.get("", checkOrigin, this.pollcontroller.getAllPolls);
this.router.post("", checkOrigin, this.pollcontroller.createPoll);
this.router.post(
"/vote/:pollId",
checkOrigin,
this.pollcontroller.voteOnPoll
);
this.router.get("/:pollId", checkOrigin, this.pollcontroller.getResults);
}
}

Expand Down

0 comments on commit f36053d

Please sign in to comment.