aguidrevitch/jquery-file-upload-middleware

Running middleware before uploading

Opened this issue · 1 comments

Before I let a user upload files, I want to perform an authentication check.

The uploading works fine if I just use the middleware like this:

app.use('/upload/blogs', function (req, res, next) {
    upload.fileHandler({
        uploadDir: function () {
            return __dirname + '\\public\\uploads\\blogs\\';
        },
        uploadUrl: function () {
            return '/uploads/blogs';
        }
    })(req, res, next);
});

If I add any sort of async middlerware prior to above code, the upload does nothing. e.g. adding the following use before the above code:

app.use(function (req, res, next) {
    var token = req.headers["x-authenticationtoken"];
    if (token == null)
        return next();
    tokenRepository.getUserByToken(token, function (result) {
            if (result.error != null) {
                req.currentUser = null;
                console.log("Not logged in");
            }
            else {
                req.currentUser = result.data;
                console.log("user authenitcated");
            }
            next();
        }
    );
});

If I comment out the async part like this, it will work:

app.use(function (req, res, next) {
//    var token = req.headers["x-authenticationtoken"];
//    if (token == null)
//        return next();
//    tokenRepository.getUserByToken(token, function (result) {
//            if (result.error != null) {
//                req.currentUser = null;
//                console.log("Not logged in");
//            }
//            else {
//                req.currentUser = result.data;
//                console.log("user authenitcated");
//            }
//            next();
//        }
//    );
    next();
});

Any ideas on what I'm doing wrong?

there's no route specified on your code
app.use(function (req, res, next) {

instead, try this approach

app.use('/upload/blogs', function (req, res, next) { var token = req.headers["x-authenticationtoken"]; if (token == null) return next(); tokenRepository.getUserByToken(token, function (result) { upload.fileHandler({ uploadDir: function () { return __dirname + '\\public\\uploads\\blogs\\'; }, uploadUrl: function () { return '/uploads/blogs'; } })(req, res, next); } }