my mentor want me to check if the user who put a sauce on the app is the same user who want to modify. he tells me i can use a condition i di!d it but nothing works
here is the code section:
exports.updateSauce = (req, res, next) => {
//console.log (req);
//recherche de la sauce dont l'id est en paramètre
sauce.findOne({ _id: req.params.id })
.then((sauce) => {
//teste si l'id du créateur de la sauce est le même que l'id du requeteur
if (sauce.userId !== req.auth.userId) {
return res.status(401).json({
error: new Error('Requête non autorisée !')
})
}
// ok, c'est le même
console.log("OK");
// effaçons le fichier image d'origine si l'on change d'image
if (req.file) { //si une image est upload
const last_filename = sauce.imageUrl.split('/images/')[1];
console.log(last_filename);
fs.unlink(`images/${last_filename}`, () => {
console.log("FICHIER EFFACE");
const sauceObject = { ...JSON.parse(req.body.sauce), imageUrl: `${req.protocol}://${req.get('host')}/images/${req.file.filename}` };
console.log(sauceObject);
console.log(req.params.id);
sauce.updateOne({ _id: req.params.id }, { ...sauceObject, _id: req.params.id })
.then(() => res.status(200).json({ message: 'Sauce modifiée !' }))
.catch(error => res.status(400).json({ error }));
});
}
else {
console.log("SANS FICHIER MODIFIE");
console.log(req.body);
const sauceObject = { ...req.body };
console.log(req.params.id);
sauce.updateOne({ _id: req.params.id }, { ...sauceObject, _id: req.params.id })
.then(() => {
console.log("updated");
return res.status(200).json({ message: 'Sauce modifiée !' })
}
)
.catch(error => res.status(400).json({ error }));
}
}
);
CodePudding user response:
Then you need to convert objectId to string before compare:
if (sauce.userId.toString() !== req.auth.userId) { //If req.auth.userId is string as you said
return res.status(401).json({
error: new Error('Requête non autorisée !')
});
}
CodePudding user response:
This looks fine but it might not work if one is an objectID and the other is a string, Can you check which might be a string in the section below:
if (sauce.userId !== mongoose.Types.ObjectId(req.auth.userId)) {
return res.status(401).json({
error: new Error('Requête non autorisée !')
})
Can you log these two sauce.userId & req.auth.userId and share the output?