Nodejs Express 4 Multer | 如果用户没有授权,请停止file upload

我正在使用multer作为express4的多部件中间件。

Expressconfiguration为使用passport作为auth middelware,但是我找不到防止file upload的方法,如果用户没有通过validation。

我想使用onFileUploadStart拒绝文件,但我找不到与“请求”对象的链接,可以匹配用户。

下面的代码用于configurationexpress和multer:

 <code> ... // 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()); </code> 

感谢您的支持

洛伦佐

编辑

我会在下面的答案,以防万一它的帮助,但答案其实很简单:你需要将两个调用移动到app.use(multer)的调用上方app.use(passport) app.use(multer) 。 Express链中的每一步都按顺序处理,所以如果您希望拒绝一个不正确的validation尝试,请处理传入file upload之前进行。


可能有更好的方法来做到这一点,但这应该让你开始。 改变你的快速configuration使用闭包,你将有完全访问reqvariables。

 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); }); 

好吧,我想我有一个解决scheme给你。 这不是一个完整的解决scheme,但它适用于您的具体情况,即在下载文件之前检查用户是否通过Passport授权。

诀窍是在你的后处理程序中使用中间件一次做一件事。 第一个护照将被调用来把用户对象放在req对象中。 然后,您检查用户是否通过身份validation。 如果是这样的话,你下载这个文件然后使用它。 这是一个示例:

 //don't add multer as a middleware to all requests. //If you do this, people will be able to upload files //in ALL YOUR 'post' handlers!!! var Multer = require('multer'); //this is a middleware to check if user is authenticated function check(req, res, next){ if(req.isAuthenticated()){ console.log(req.user); next(); } else{ res.send(401); } } //this is a middleware to be called after file is downloaded function finish(req, res, next){ var filePath = req.files.file.path; res.send("Hello " + req.user.name + "! Your file was uploaded to " + filePath); } //this is the route handler. First check auth. If so, //proceed to multer middleware to download file //lastly, use the file as you need app.post('/test', [check, Multer(), finish]); 

这仅适用于Passport不使用身体数据对用户进行身份validation:它使用不在身体中的会话。 因此,您可以使用Passport并获取用户数据,但不能确保在开始下载文件之前parsing了所有非文件字段(因为它们都以express请求stream的forms出现在一起)

从multer api文档中,你甚至可以停止上传文件 – 只需从事件处理程序返回false,文件将不会被处理或到达文件系统。