Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions server/models/product.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// models/product.ts
import { Schema, model, Document } from "mongoose";

// Define the Product Schema
const productSchema = new Schema({
storeName: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
imgUrl: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
});

// Define the Product interface extending Document
interface IProduct extends Document {
storeName: string;
price: number;
imgUrl: string;
description: string;
}

// Create the Product model
const Product = model<IProduct>("Product", productSchema);

export default Product;
68 changes: 34 additions & 34 deletions server/routes/community.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,27 @@
import express from "express";
import bcrypt from "bcrypt";

import jwt from "jsonwebtoken";
import { CommunityModel, UserModel } from "../models/user";
import { signup } from "./signup";
import { login } from "./login";
import { authorizeCommunity, authorizeUser } from "../middlewares/authorize";
import { createContest } from "../controllers/createContest";
import { findContest } from "../controllers/findContest";
import { populateContest } from "../middlewares/populateContest";
import { joinContestCommunity } from "../controllers/joinContestCommunity";
import { pollContest } from "../utils/mongoPolling";
import { CONTEST_SECRET } from "../server";

import { addProducts, getProducts } from "./product";
import { authorizeCommunity, authorizeUser } from "../middlewares/authorize";
import { checkContest } from "../utils/checkContest";
import { specialTransactions } from "../controllers/transaction";

const community = express.Router();

// Define the route before applying authorization middleware
community.get("/product/list", getProducts);

// Apply authorization middleware after defining the routes that don't need it
community.use(authorizeCommunity);

community.post("/signup", async (req, res) => {
Expand All @@ -31,11 +36,12 @@ community.post("/create/contest", createContest);

community.get("/contest", findContest);

community.get("/auth",(req,res)=>{
return res.status(200).json({message:"Authenticated."});
})
community.get("/auth", (req, res) => {
return res.status(200).json({ message: "Authenticated." });
});

community.post("/join", populateContest);
community.post("/product/list", addProducts);



Expand Down Expand Up @@ -93,40 +99,34 @@ community.post("/contest/pay-reward",checkContest,async(req:any,res:any)=>{

// NEW: Fetch All Users Route
community.get("/users", async (req, res) => {
try {
// Fetch all users with selected fields (e.g., name and _id)
const users = await UserModel.find({}, { name: 1, _id: 1 });

// Respond with the list of users
res.status(200).json({ users });
} catch (error) {
console.error("Error fetching users:", error);
res.status(500).json({ message: "An error occurred while fetching users." });
}
try {
// Fetch all users with selected fields (e.g., name and _id)
const users = await UserModel.find({}, { name: 1, _id: 1 });

// Respond with the list of users
res.status(200).json({ users });
} catch (error) {
console.error("Error fetching users:", error);
res.status(500).json({
message: "An error occurred while fetching users.",
});
}
});

community.get("/join/:token", (req: any, res: any) => {
const { token } = req.params;
console.log("dndjfbdfj hellllllllllllllllllllllo");
const verify: any = jwt.verify(token, String(CONTEST_SECRET));

community.get("/join/:token", (req:any, res:any) => {
const {token}= req.params;
console.log("dndjfbdfj hellllllllllllllllllllllo");
const verify:any = jwt.verify(token,String(CONTEST_SECRET));

console.log(verify);
console.log(verify,"this is coolll");

if(!verify){
return res.status(500).json({message:"You can not join the room."});
}

req.contest = verify;
joinContestCommunity(req,res);
console.log(verify);
console.log(verify, "this is coolll");


if (!verify) {
return res.status(500).json({ message: "You can not join the room." });
}




req.contest = verify;
joinContestCommunity(req, res);
});


export { community };
75 changes: 75 additions & 0 deletions server/routes/product.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { Request, Response } from "express";
import Product from "../models/product";

/**
* Add a list of products to the database
*/
export const addProducts = async (
req: Request,
res: Response
): Promise<void> => {
const products = req.body;

// Check if the request body is an array of products
if (!Array.isArray(products)) {
res.status(400).json({
success: false,
message: "Input should be an array of products.",
});
return;
}

// Define required fields for each product
const requiredFields = ["storeName", "price", "imgUrl", "description"];

// Validate that all required fields are present for each product
for (const product of products) {
for (const field of requiredFields) {
if (!product[field]) {
res.status(400).json({
success: false,
message:
"All fields (storeName, price, imgUrl, description) are required.",
});
return;
}
}
}

try {
const savedProducts = await Product.insertMany(products);
res.status(201).json({
success: true,
message: "Products saved successfully.",
data: savedProducts,
});
} catch (error) {
console.error("Error saving products:", error);
res.status(500).json({
success: false,
message: "An error occurred while saving products.",
});
}
};

/**
* Fetch all products from the database
*/
export const getProducts = async (
req: Request,
res: Response
): Promise<void> => {
try {
const products = await Product.find();
res.status(200).json({
success: true,
data: products,
});
} catch (error) {
console.error("Error fetching products:", error);
res.status(500).json({
success: false,
message: "An error occurred while fetching products.",
});
}
};
99 changes: 54 additions & 45 deletions server/routes/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,27 @@ import { registerContest } from "../controllers/registerContest";
import { CONTEST_SECRET, JWT_SECRET } from "../server";
import { submitProblems } from "../controllers/submitProblems";
import { pollContest } from "../utils/mongoPolling";
import { getProducts } from "./product";

require("dotenv");

const user = express.Router();

// Signup Route
user.post("/signup", async (req, res) => {
signup(req, res, "U");
signup(req, res, "U");
});

user.get("/product/list", getProducts);

// Login Route
user.post("/login", async (req, res) => {
login(req, res, "U");
login(req, res, "U");
});

// Authentication Check
user.get("/auth", (req, res) => {
return res.status(200).json({ message: "Authenticated." });
return res.status(200).json({ message: "Authenticated." });
});

// Contest Routes
Expand All @@ -34,52 +38,57 @@ user.post("/contest/register", registerContest);

// Join Contest Route with Token Verification
user.get("/join/:token", (req, res) => {
const { token } = req.params;

try {
const verify = jwt.verify(token, String(CONTEST_SECRET));
console.log(verify, "this is coolll");

if (!verify) {
return res.status(500).json({ message: "You cannot join the room." });
} else if (!verify.contest_id) {
throw new Error("Token does not contain contest ID.");
const { token } = req.params;

try {
const verify = jwt.verify(token, String(CONTEST_SECRET));
console.log(verify, "this is coolll");

if (!verify) {
return res
.status(500)
.json({ message: "You cannot join the room." });
} else if (!verify.contest_id) {
throw new Error("Token does not contain contest ID.");
}

res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");

const data = JSON.stringify({
message: "Update from Stream 1",
timestamp: new Date().toISOString(),
contest: verify,
});
res.write(`data: ${data}\n\n`);

const sendEvent = async () => {
const contestRankings = await pollContest(verify.contest_id);
const kapa = {
message: "Update from Stream 1",
rankings: contestRankings.rankings,
timestamp: new Date().toISOString(),
};
const data = JSON.stringify(kapa);
res.write(`data: ${data}\n\n`);
};

sendEvent();

const interval = setInterval(sendEvent, 4000);

req.on("close", () => {
clearInterval(interval);
res.end();
});
} catch (error) {
console.error("Error verifying token:", error);
return res.status(500).json({ message: "Invalid token." });
}

res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");

const data = JSON.stringify({ message: 'Update from Stream 1', timestamp: new Date().toISOString() ,contest:verify});
res.write(`data: ${data}\n\n`);

const sendEvent = async () => {
const contestRankings = await pollContest(verify.contest_id);
const kapa = {
message: "Update from Stream 1",
rankings: contestRankings.rankings,
timestamp: new Date().toISOString(),
};
const data = JSON.stringify(kapa);
res.write(`data: ${data}\n\n`);
};

sendEvent();

const interval = setInterval(sendEvent, 4000);

req.on("close", () => {
clearInterval(interval);
res.end();
});
} catch (error) {
console.error("Error verifying token:", error);
return res.status(500).json({ message: "Invalid token." });
}
});

// Problem Submission Route
user.post("/submit", submitProblems);


export { user };