how to sanitize file upload path before upload.basically, I want to prevent ../../../etc/password this kind of attack.
I am getting a problem with my code on this section await Jimp.read(reqImage.data) how to sanitize before I send it to Jimp. how to handle this.
here is my code
if (req.files) {
// catch image from form
const reqImage = req.files.aImage;
// check image size
if (req.files.aImage.size >= 200000) {
req.flash('error', 'Improper image size !');
return res.status(302).redirect('back');
}
// check file name
if (req.files.aImage.name.match(/\.\.\//g) !== null) {
req.flash('error', 'Image Name Incorrect !');
return res.status(302).redirect('back');
}
// check Image extention
function isImage() {
if (req.files !== null) {
const extension = req.files.aImage.mimetype;
switch (extension) {
case 'image/jpg':
return true;
case 'image/jpeg':
return true;
case 'image/png':
return true;
default:
return false;
}
}
}
// check if image is image is only jpg, jpeg, png
if (!isImage(req.files)) {
req.flash('error', 'Image Type Wrong. Supported Types (jpg|jpeg|png) !');
return res.status(302).redirect('back');
}
const uploadPath = `${folder}${audioImage}`;
// move file to jimp to resize
await Jimp.read(reqImage.data) // problem with jimp section when i pass req.files.aImage.data
//it will showing path traversal error unsanitized input
.then((image) => {
image
.scaleToFit(404, 223, [
Jimp.HORIZONTAL_ALIGN_CENTER,
Jimp.VERTICAL_ALIGN_MIDDLE,
])
.quality(60)
.write(uploadPath); // upload the image to the folder
})
.catch((err) => {
// if error show this error
if (err) {
req.flash('error', 'Something wrong in image Uploading !');
return res.status(302).redirect('back');
}
});
}