I'm looking for a way to prevent upload in case of not authenticated user
I'm using Express which is configured to use passport as auth middelware.
I thought to use onFileUploadStart to reject the file, but I cannot find a link with "request" object, with which it would be possible to match the user.
Thanks
Lorenzo
Load the auth middleware before multer.
...
// Multipart file upload
app.use(multer(
{
dest: wwwroot + path.sep + 'uploaded' + path.sep,
onFileUploadStart: function (file) {
//TODO : apply security check : user auth, file size, number...
console.log(file.fieldname + ' is starting ...')
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ' uploaded to ' + file.path)
}
}));
...
app.use(passport.auth.initialize());
app.use(passport.auth.session());
I've tried to put the last 2 lines before multer init, but no way. Is it some other middleware for security you're referring to? Or Is there a way to access request object inside onFileUploadStart()? In that case I would be able to check the user.
Thanks
@hacksparrow Could you give me advice, please? I can't catch if it is a limit of express, of multer , both, a versions uncompliancy or myself in making mistake with the config, Thanks
@lorenzotsi You can do the auth check on the route that receives the files. I use passportjs and get a req.user I can do checks on.
@sigurdga Thanks for your support, but that can be applied after. I mean, first the file is uploaded (that is what I'm trying to prevent), in the route I could then cancel the just uploaded file in case user not logged in. I hoped in a better solution.
@lorenzotsi You need to use multer per route instead of globally. (https://github.com/jpfluger/multer/blob/examples/multer-upload-files-to-different-directories.md)
Then you can add an auth middleware before multer like this:
router.post('/uploads', function (req, res, next) {
if (!authorized) {
res.send(403);
} else {
next();
}
},
multer({ dest: '/uploads/' }),
function (req, res, next) {
// whatever you were planning to do.
});
I know it's late, but I hope it ends up helping someone.
But what happen if i need to parser the form data to get the authentication value? What should i do in this case?
Most helpful comment
But what happen if i need to parser the form data to get the authentication value? What should i do in this case?