add an example of using dollar eq

This commit is contained in:
erik-krogh 2023-05-31 13:08:20 +02:00
Родитель e24b45b423
Коммит 7d801e05ee
Не найден ключ, соответствующий данной подписи
3 изменённых файлов: 33 добавлений и 8 удалений

Просмотреть файл

@ -69,8 +69,16 @@ object, so this code is vulnerable to a NoSQL injection attack.
<sample src="examples/NoSqlInjection.js" />
<p>
To fix this vulnerability, we can check that the user input is a
literal value and not a query object before using it in a query.
To fix this vulnerability we can use the <code>$eq</code> operator
to ensure that the user input is interpreted as a literal value
and not as a query object:
</p>
<sample src="examples/NoSqlInjectionFix2.js" />
<p>
Alternatively check that the user input is a
literal value and not a query object before using it:
</p>
<sample src="examples/NoSqlInjectionFix.js" />

Просмотреть файл

@ -11,11 +11,7 @@ app.use(express.urlencoded({ extended: false }));
app.delete("/api/delete", async (req, res) => {
let id = req.body.id;
if (typeof id !== "string") {
res.status(400).json({ status: "error" });
return;
}
await Todo.deleteOne({ _id: id }); // GOOD: id is guaranteed to be a string
await Todo.deleteOne({ _id: { $eq: id } }); // GOOD: using $eq operator for the comparison
res.json({ status: "ok" });
});
});

Просмотреть файл

@ -0,0 +1,21 @@
const express = require("express");
const mongoose = require("mongoose");
const Todo = mongoose.model(
"Todo",
new mongoose.Schema({ text: { type: String } }, { timestamps: true })
);
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.delete("/api/delete", async (req, res) => {
let id = req.body.id;
if (typeof id !== "string") {
res.status(400).json({ status: "error" });
return;
}
await Todo.deleteOne({ _id: id }); // GOOD: id is guaranteed to be a string
res.json({ status: "ok" });
});