Nodejs Express 4 Multer | Stop file upload if user not authorized

LorenzoGi picture LorenzoGi · Aug 23, 2014 · Viewed 7.4k times · Source

I'm using multer as multipart middelware for express4.

Express is configured to use passport as auth middelware, but I cannot find a way to prevent file upload if the user is not authenticated.

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.

Below code use in configuring express vs 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());   

Answer

morloch picture morloch · Sep 18, 2014

EDIT

I'll leave the answer below in case it helps, but the answer is actually quite simple: you need to move the two calls to app.use(passport) above the call to app.use(multer). Each step in the express chain is processed in order, so if you wish reject a bad auth attempt, do it before you handle the incoming file upload.


There is probably a better way to do this, but this should get you started. Change your express config to use a closure and you'll have full access to the req variable.

app.use(function(req, res, next) {
  var handler = multer({
    dest: wwwroot + path.sep + 'uploaded' + path.sep, 
    onFileUploadStart: function (file) {
      // You now have access to req
      console.dir(req);
      console.log(file.fieldname + ' is starting ...')
    },
    onFileUploadComplete: function (file) {
      console.log(file.fieldname + ' uploaded to  ' + file.path)
    }
  });
  handler(req, res, next);
});