Skip to content

Commit 2e75e16

Browse files
Potential fix for code scanning alert no. 3: Database query built from user-controlled sources
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
1 parent 8a6c2a1 commit 2e75e16

2 files changed

Lines changed: 23 additions & 1 deletion

File tree

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@
1414
"express": "^4.18.2",
1515
"express-rate-limit": "^7.5.0",
1616
"jsonwebtoken": "^9.0.2",
17-
"mongoose": "^8.12.1"
17+
"mongoose": "^8.12.1",
18+
"joi": "^17.13.3"
1819
},
1920
"devDependencies": {
2021
"nodemon": "^3.0.2"

routes/books.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,19 @@ const express = require('express');
22
const router = express.Router();
33
const Book = require('../models/book');
44
const auth = require('../middleware/auth');
5+
const Joi = require('joi');
6+
7+
const bookSchema = Joi.object({
8+
title: Joi.string().required(),
9+
author: Joi.string().required(),
10+
publicationYear: Joi.number().integer().required(),
11+
isbn: Joi.string().required(),
12+
summary: Joi.string().required(),
13+
coverImage: Joi.string().uri().required(),
14+
category: Joi.string().required(),
15+
pageCount: Joi.number().integer().required(),
16+
language: Joi.string().required()
17+
});
518

619
router.get('/', auth, async (req, res) => {
720
try {
@@ -25,6 +38,10 @@ router.get('/:id', auth, async (req, res) => {
2538
});
2639

2740
router.post('/', auth, async (req, res) => {
41+
const { error } = bookSchema.validate(req.body);
42+
if (error) {
43+
return res.status(400).json({ message: error.details[0].message });
44+
}
2845
const book = new Book({
2946
title: req.body.title,
3047
author: req.body.author,
@@ -46,6 +63,10 @@ router.post('/', auth, async (req, res) => {
4663
});
4764

4865
router.put('/:id', auth, async (req, res) => {
66+
const { error } = bookSchema.validate(req.body);
67+
if (error) {
68+
return res.status(400).json({ message: error.details[0].message });
69+
}
4970
try {
5071
const book = await Book.findByIdAndUpdate(req.params.id, req.body, { new: true });
5172
if (!book) {

0 commit comments

Comments
 (0)