Nodejs Express 4静音器|如果用户未授权,则停止文件上传 [英] Nodejs Express 4 Multer | Stop file upload if user not authorized
问题描述
我正在使用multer
作为express4的多部分中间件.
I'm using multer
as multipart middelware for express4.
Express配置为使用通行证作为auth中间件,但是如果用户未通过身份验证,我无法找到一种方法来阻止文件上传.
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.
我以为可以使用onFileUploadStart拒绝文件,但是我找不到与"request"对象的链接,通过该链接可以匹配用户.
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.
以下代码用于配置Express与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());
推荐答案
编辑
如果有帮助,我将在下面保留答案,但答案实际上非常简单:您需要将两个调用移到app.use(passport)
上方上,将调用移到app.use(multer)
. Express链中的每个步骤都是按顺序处理的,因此,如果您希望拒绝错误的身份验证尝试,请在处理传入文件上载之前 进行.
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.
也许有更好的方法可以做到这一点,但这应该可以帮助您入门.更改您的express配置以使用闭包,您将拥有对req
变量的完全访问权限.
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);
});
这篇关于Nodejs Express 4静音器|如果用户未授权,则停止文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!