Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Major Changes #1

Open
wants to merge 22 commits into
base: main
Choose a base branch
from
Open
31 changes: 16 additions & 15 deletions Backend/Controllers/questionController.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,34 @@ const logger = require('../utils/logger');
const promClient = require('prom-client');

const counter = new promClient.Counter({
name: 'question_served',
name: 'questions_served',
help: 'The number of questions served'
});

const getRandomQuestion = async (req, res) => {
const getAllQuestions = async (req, res) => {
try {
const count = await Question.countDocuments();
const questions = await Question.find();
console.log(questions)
const count = questions.length;

console.log('Total questions count:', count);
logger.info('Total questions count:', count);

if (count === 0) {
return res.status(404).json({ msg: 'No questions found' });
}
const random = Math.floor(Math.random() * count);
const question = await Question.findOne().skip(random);
logger.info('Random question:', question);
console.log('Random question:', question);

if (!question) {
return res.status(404).json({ msg: 'No question found' });
}
counter.inc(count); // Increment the counter by the number of questions served

counter.inc();
const questionsWithoutAnswers = questions.map(({ _id, question, options }) => ({
_id,
question,
options
}));

res.json(question);
res.json(questionsWithoutAnswers);
} catch (err) {
logger.error('Error in /random-question endpoint:', err.message);
logger.error('Error in /random-question endpoint:', err.message);
logger.error('Error in /all-questions endpoint:', err.message);
res.status(500).send('Server Error');
}
};
Expand All @@ -49,4 +50,4 @@ const checkAnswer = async (req, res) => {
}
};

module.exports = { getRandomQuestion, checkAnswer };
module.exports = { getAllQuestions, checkAnswer };
35 changes: 34 additions & 1 deletion Backend/Controllers/userController.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,39 @@ const createUser = async (req, res) => {
}
};

// Return all users (Leaderboard)
const getAllUsers = async (req, res) => {
try {
const users = await User.find().sort({ score: -1 }); // Sorting by score in descending order
res.status(200).json({
message: 'Users retrieved successfully',
users
});
} catch (error) {
res.status(500).json({
message: 'Failed to retrieve users',
error: error.message
});
}
};

// Clear all users
const clearUsers = async (req, res) => {
try {
await User.deleteMany({});
res.status(200).json({
message: 'All users cleared successfully'
});
} catch (error) {
res.status(500).json({
message: 'Failed to clear users',
error: error.message
});
}
};

module.exports = {
createUser
createUser,
clearUsers,
getAllUsers
};
4 changes: 2 additions & 2 deletions Backend/Routes/questionRoutes.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const express = require('express');
const router = express.Router();
const { getRandomQuestion, checkAnswer } = require('../Controllers/questionController');
const { getAllQuestions, checkAnswer } = require('../Controllers/questionController');

router.get('/random-question', getRandomQuestion);
router.get('/all-questions', getAllQuestions);

router.post('/check-answer', checkAnswer);

Expand Down
6 changes: 5 additions & 1 deletion Backend/Routes/userRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@ const express = require('express');
const router = express.Router();

const {
createUser
createUser,
getAllUsers,
clearUsers
} = require('../Controllers/userController')

router.post('/create', createUser)
router.get('/', getAllUsers);
router.delete('/clear', clearUsers);

module.exports = router
24 changes: 24 additions & 0 deletions Backend/app.log
Original file line number Diff line number Diff line change
Expand Up @@ -415,3 +415,27 @@
2024-08-22T18:35:34.909Z info: MongoDB connected
2024-08-22T18:35:36.836Z info: Server started on port 7000
2024-08-22T18:35:37.664Z info: MongoDB connected
2024-08-22T19:04:04.280Z info: Server started on port 7000
2024-08-22T19:04:04.687Z info: MongoDB connected
2024-08-22T19:17:29.852Z info: Server started on port 7000
2024-08-22T19:17:30.243Z info: MongoDB connected
2024-08-22T19:17:41.157Z info: Total questions count:
2024-08-22T19:18:28.554Z info: Total questions count:
2024-08-22T19:21:50.447Z info: Total questions count:
2024-08-22T19:22:00.751Z info: Total questions count:
2024-08-22T19:26:53.519Z info: Total questions count:
2024-08-22T19:45:33.213Z info: Total questions count:
2024-08-22T19:48:39.514Z info: Total questions count:
2024-08-22T19:53:24.393Z info: Server started on port 7000
2024-08-22T19:53:24.826Z info: MongoDB connected
2024-08-22T19:56:06.610Z info: Total questions count:
2024-08-23T05:40:56.224Z info: Server started on port 7000
2024-08-23T05:40:57.560Z info: MongoDB connected
2024-08-23T06:09:32.762Z info: Server started on port 7000
2024-08-23T06:09:33.707Z info: MongoDB connected
2024-08-23T06:10:35.182Z info: Total questions count:
2024-08-23T06:39:01.409Z info: Server started on port 7000
2024-08-23T06:39:02.866Z info: MongoDB connected
2024-08-23T06:43:24.967Z info: Total questions count:
2024-08-29T07:03:32.939Z info: Server started on port 7000
2024-08-29T07:03:43.716Z info: MongoDB connected
File renamed without changes.
4 changes: 2 additions & 2 deletions Backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js",
"dev": "nodemon server.js"
"start": "node index.js",
"dev": "nodemon index.js"
},
"keywords": [],
"author": "",
Expand Down
15 changes: 15 additions & 0 deletions Backend/vercel.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"version": 2,
"builds": [
{
"src": "./index.js",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/api/(.*)",
"dest": "/"
}
]
}
2 changes: 1 addition & 1 deletion Frontend/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/jpg" href="../Frontend/src/assets/encode.jpeg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Encode W3 Day</title>
<title>Encode Intro Session</title>
</head>
<body>
<div id="root"></div>
Expand Down
2 changes: 1 addition & 1 deletion Frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"dev": "vite --host",
"build": "vite build",
"lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
Expand Down
107 changes: 107 additions & 0 deletions Frontend/pages/Admin.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import '../src/Admin.css'; // Import the CSS file for styling

const Admin = () => {
const [password, setPassword] = useState('');
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [error, setError] = useState('');
const [leaderboard, setLeaderboard] = useState([]);
const [LBButtonClicked, setLBButtonClicked] = useState(false);
const correctPassword = import.meta.env.VITE_ADMIN_PASSWORD;
const backendRoute = import.meta.env.VITE_BACKEND_ROUTE;

useEffect(() => {
setLBButtonClicked(false);
}, []); // Adding an empty dependency array to run the effect only once on mount

const handlePasswordChange = (e) => {
setPassword(e.target.value);
};

const handleLogin = () => {
if (password === correctPassword) {
setIsAuthenticated(true);
setError('');
} else {
setError('Incorrect password. Please try again.');
}
};

const handleClearUsers = async () => {
try {
await axios.delete(`${backendRoute}/clear`);
alert('All users cleared successfully.');
setLeaderboard([]); // Clear leaderboard after users are deleted
setLBButtonClicked(true);
} catch (error) {
console.error('Error clearing users:', error);
alert('Failed to clear users.');
}
};

const handleShowLeaderboard = async () => {
try {
const response = await axios.get(`${backendRoute}/`);
setLeaderboard(response.data.users); // Update state with leaderboard data
setLBButtonClicked(true);
} catch (error) {
console.error('Error fetching leaderboard:', error);
alert('Failed to fetch leaderboard.');
}
};

return (
<div className="admin-container">
{!isAuthenticated ? (
<div className="login-container">
<h2>Admin Login</h2>
<input
type="password"
value={password}
onChange={handlePasswordChange}
placeholder="Enter admin password"
className="password-input"
/>
<button onClick={handleLogin} className="login-button">Login</button>
{error && <p className="error-message">{error}</p>}
</div>
) : (
<div className="admin-actions">
<button onClick={handleClearUsers} className="action-button clear-button">Clear Users</button>
<button onClick={handleShowLeaderboard} className="action-button leaderboard-button">Show Leaderboard</button>

{LBButtonClicked && (
leaderboard.length > 0 ? (
<div className="leaderboard-table">
<h3>Leaderboard</h3>
<table>
<thead>
<tr>
<th>Name</th>
<th>Roll Number</th>
<th>Score</th>
</tr>
</thead>
<tbody>
{leaderboard.map((user, index) => (
<tr key={index}>
<td>{user.name}</td>
<td>{user.rollNo}</td>
<td>{user.score}</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<h2>No Users Yet!</h2>
)
)}
</div>
)}
</div>
);
};

export default Admin;
Loading