This commit is contained in:
shivam 2025-03-18 22:33:15 +05:30
commit cca241b42a
5 changed files with 203 additions and 126 deletions

View File

@ -41,3 +41,71 @@ exports.publishResult = async (data, authorization) => {
announcement_time = VALUES(announcement_time) announcement_time = VALUES(announcement_time)
`, [teams[0].id, date, result, announcement_time]); `, [teams[0].id, date, result, announcement_time]);
}; };
exports.getResultsByTeam = async (teamName, authorization) => {
const token = authorization?.split(' ')[1];
const [admin] = await db.query('SELECT id FROM admins WHERE session_token = ?', [token]);
if (!admin) throw { status: 401, message: 'Unauthorized' };
if (!teamName) throw { status: 400, message: 'Team name is required' };
return db.query(`
SELECT r.*, t.name AS team_name
FROM results r
JOIN teams t ON r.team_id = t.id
WHERE t.name = ?
`, [teamName.toUpperCase()]);
};
exports.createTeam = async (data, authorization) => {
const token = authorization?.split(' ')[1];
const [admin] = await db.query('SELECT id FROM admins WHERE session_token = ?', [token]);
if (!admin) throw { status: 401, message: 'Unauthorized' };
const { name } = data;
if (!name) throw { status: 400, message: 'Name is required' };
await db.query('INSERT INTO teams (name) VALUES (?)', [name.toUpperCase()]);
return { success: true, message: 'Team created successfully' };
};
exports.updateTeam = async (id, data, authorization) => {
const token = authorization?.split(' ')[1];
const [admin] = await db.query('SELECT id FROM admins WHERE session_token = ?', [token]);
if (!admin) throw { status: 401, message: 'Unauthorized' };
const { name } = data;
if (!name) throw { status: 400, message: 'Name is required' };
await db.query('UPDATE teams SET name = ? WHERE id = ?', [name.toUpperCase(), id]);
return { success: true, message: 'Team updated successfully' };
};
exports.deleteTeam = async (id, authorization) => {
const token = authorization?.split(' ')[1];
const [admin] = await db.query('SELECT id FROM admins WHERE session_token = ?', [token]);
if (!admin) throw { status: 401, message: 'Unauthorized' };
await db.query('DELETE FROM teams WHERE id = ?', [id]);
return { success: true, message: 'Team deleted successfully' };
};
exports.updateResultById = async (id, data, authorization) => {
const token = authorization?.split(' ')[1];
const [admin] = await db.query('SELECT id FROM admins WHERE session_token = ?', [token]);
if (!admin) throw { status: 401, message: 'Unauthorized' };
const { team, date, result, announcement_time } = data;
const teams = await db.query('SELECT id FROM teams WHERE name = ?', [team.toUpperCase()]);
if (!teams.length) throw { status: 400, message: 'Team does not exist' };
await db.query(
'UPDATE results SET team_id = ?, result_date = ?, result = ?, announcement_time = ? WHERE id = ?',
[teams[0].id, date, result, announcement_time, id]
);
};
exports.deleteResultById = async (id, authorization) => {
const token = authorization?.split(' ')[1];
const [admin] = await db.query('SELECT id FROM admins WHERE session_token = ?', [token]);
if (!admin) throw { status: 401, message: 'Unauthorized' };
await db.query('DELETE FROM results WHERE id = ?', [id]);
};

View File

@ -9,57 +9,3 @@ exports.getAllTeams = async (req, res) => {
res.status(500).json({ error: 'Failed to fetch teams' }); res.status(500).json({ error: 'Failed to fetch teams' });
} }
}; };
exports.createTeam = async (req, res) => {
try {
const { name } = req.body;
if (!name) {
return res.status(400).json({ error: 'Name is required' });
}
await db.query(
'INSERT INTO teams (name) VALUES (?)',
[name.toUpperCase()]
);
res.status(201).json({ success: true, message: 'Team created successfully' });
} catch (error) {
console.error('Error creating team:', error);
res.status(500).json({ error: 'Failed to create team' });
}
};
exports.updateTeam = async (req, res) => {
try {
const { id } = req.params;
const { name } = req.body;
if (!name) {
return res.status(400).json({ error: 'At least name is required' });
}
const fields = ['name = ?'];
const values = [name.toUpperCase(), id];
await db.query(`UPDATE teams SET ${fields.join(', ')} WHERE id = ?`, values);
res.json({ success: true, message: 'Team updated successfully' });
} catch (error) {
console.error('Error updating team:', error);
res.status(500).json({ error: 'Failed to update team' });
}
};
exports.deleteTeam = async (req, res) => {
try {
const { id } = req.params;
await db.query('DELETE FROM teams WHERE id = ?', [id]);
res.json({ success: true, message: 'Team deleted successfully' });
} catch (error) {
console.error('Error deleting team:', error);
res.status(500).json({ error: 'Failed to delete team' });
}
};

View File

@ -29,7 +29,7 @@
} }
}, },
{ {
"name": "Publish Result", "name": "Publish Result (Admin)",
"request": { "request": {
"method": "POST", "method": "POST",
"header": [ "header": [
@ -55,6 +55,77 @@
} }
} }
}, },
{
"name": "Update Result (Admin)",
"request": {
"method": "PUT",
"header": [
{
"key": "Content-Type",
"value": "application/json"
},
{
"key": "Authorization",
"value": "Bearer <SESSION_TOKEN>"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"team\": \"UPDATED TEAM\",\n \"date\": \"2025-03-12\",\n \"result\": \"55\",\n \"announcement_time\": \"03:00:00\"\n}"
},
"url": {
"raw": "http://localhost:3000/admin/results/1",
"protocol": "http",
"host": ["localhost"],
"port": "3000",
"path": ["admin", "results", "1"]
}
}
},
{
"name": "Delete Result (Admin)",
"request": {
"method": "DELETE",
"header": [
{
"key": "Authorization",
"value": "Bearer <SESSION_TOKEN>"
}
],
"url": {
"raw": "http://localhost:3000/admin/results/1",
"protocol": "http",
"host": ["localhost"],
"port": "3000",
"path": ["admin", "results", "1"]
}
}
},
{
"name": "Get Results By Team (Admin)",
"request": {
"method": "GET",
"header": [
{
"key": "Authorization",
"value": "Bearer <SESSION_TOKEN>"
}
],
"url": {
"raw": "http://localhost:3000/admin/results?team=BIKANER SUPER",
"protocol": "http",
"host": ["localhost"],
"port": "3000",
"path": ["admin", "results"],
"query": [
{
"key": "team",
"value": "BIKANER SUPER"
}
]
}
}
},
{ {
"name": "Get All Teams", "name": "Get All Teams",
"request": { "request": {
@ -70,7 +141,7 @@
} }
}, },
{ {
"name": "Create Team", "name": "Create Team (Admin)",
"request": { "request": {
"method": "POST", "method": "POST",
"header": [ "header": [
@ -88,16 +159,16 @@
"raw": "{\n \"name\": \"NEW TEAM\"\n}" "raw": "{\n \"name\": \"NEW TEAM\"\n}"
}, },
"url": { "url": {
"raw": "http://localhost:3000/api/teams", "raw": "http://localhost:3000/admin/teams",
"protocol": "http", "protocol": "http",
"host": ["localhost"], "host": ["localhost"],
"port": "3000", "port": "3000",
"path": ["api", "teams"] "path": ["admin", "teams"]
} }
} }
}, },
{ {
"name": "Update Team", "name": "Update Team (Admin)",
"request": { "request": {
"method": "PUT", "method": "PUT",
"header": [ "header": [
@ -115,16 +186,16 @@
"raw": "{\n \"name\": \"UPDATED TEAM\"\n}" "raw": "{\n \"name\": \"UPDATED TEAM\"\n}"
}, },
"url": { "url": {
"raw": "http://localhost:3000/api/teams/1", "raw": "http://localhost:3000/admin/teams/1",
"protocol": "http", "protocol": "http",
"host": ["localhost"], "host": ["localhost"],
"port": "3000", "port": "3000",
"path": ["api", "teams", "1"] "path": ["admin", "teams", "1"]
} }
} }
}, },
{ {
"name": "Delete Team", "name": "Delete Team (Admin)",
"request": { "request": {
"method": "DELETE", "method": "DELETE",
"header": [ "header": [
@ -134,11 +205,11 @@
} }
], ],
"url": { "url": {
"raw": "http://localhost:3000/api/teams/1", "raw": "http://localhost:3000/admin/teams/1",
"protocol": "http", "protocol": "http",
"host": ["localhost"], "host": ["localhost"],
"port": "3000", "port": "3000",
"path": ["api", "teams", "1"] "path": ["admin", "teams", "1"]
} }
} }
}, },
@ -156,48 +227,6 @@
} }
} }
}, },
{
"name": "Health Check",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "http://localhost:3000/api/health",
"protocol": "http",
"host": ["localhost"],
"port": "3000",
"path": ["api", "health"]
}
}
},
{
"name": "Test Sanitization",
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"name\": \"<script>alert('xss');</script>\"\n}"
},
"url": {
"raw": "http://localhost:3000/api/teams",
"protocol": "http",
"host": [
"localhost"
],
"port": "3000",
"path": [
"api",
"teams"
]
}
}
},
{ {
"name": "Get Monthly Results", "name": "Get Monthly Results",
"request": { "request": {

View File

@ -22,4 +22,58 @@ router.post('/results', validateResult, async (req, res, next) => {
} }
}); });
router.put('/results/:id', validateResult, async (req, res, next) => {
try {
await adminController.updateResultById(req.params.id, req.body, req.headers.authorization);
res.json({ success: true });
} catch (error) {
next(error);
}
});
router.delete('/results/:id', async (req, res, next) => {
try {
await adminController.deleteResultById(req.params.id, req.headers.authorization);
res.json({ success: true });
} catch (error) {
next(error);
}
});
router.get('/results', async (req, res, next) => {
try {
const data = await adminController.getResultsByTeam(req.query.team, req.headers.authorization);
res.json(data);
} catch (error) {
next(error);
}
});
router.post('/teams', async (req, res, next) => {
try {
const result = await adminController.createTeam(req.body, req.headers.authorization);
res.json(result);
} catch (error) {
next(error);
}
});
router.put('/teams/:id', async (req, res, next) => {
try {
const result = await adminController.updateTeam(req.params.id, req.body, req.headers.authorization);
res.json(result);
} catch (error) {
next(error);
}
});
router.delete('/teams/:id', async (req, res, next) => {
try {
const result = await adminController.deleteTeam(req.params.id, req.headers.authorization);
res.json(result);
} catch (error) {
next(error);
}
});
module.exports = router; module.exports = router;

View File

@ -1,27 +1,7 @@
const express = require('express'); const express = require('express');
const router = express.Router(); const router = express.Router();
const teamController = require('../controllers/teamController'); const teamController = require('../controllers/teamController');
const { validateTeam } = require('../middlewares/validation');
const db = require('../db');
async function requireAdmin(req, res, next) {
try {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Unauthorized' });
const [admin] = await db.query('SELECT id FROM admins WHERE session_token = ?', [token]);
if (!admin) return res.status(401).json({ error: 'Unauthorized' });
next();
} catch {
res.status(401).json({ error: 'Unauthorized' });
}
}
router.get('/', teamController.getAllTeams); router.get('/', teamController.getAllTeams);
router.post('/', requireAdmin, validateTeam, teamController.createTeam);
router.put('/:id', requireAdmin, validateTeam, teamController.updateTeam);
router.delete('/:id', requireAdmin, teamController.deleteTeam);
module.exports = router; module.exports = router;