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

后端 未结 3 953
南旧
南旧 2021-02-09 01:29

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 up

3条回答
  •  萌比男神i
    2021-02-09 02:02

    Okay I think I got a solution for you. It is not a complete solution for my own problems, but it serves for your specific case, which is checking if a user is authorized through Passport before downloading the file.

    The trick is to use middlewares in your post handlers to do one thing at a time. First passport will be called to put user object in the req object. Then, you check if user is authenticated. If it is the case, you download the file and then use it. Here's a sample:

    //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]);
    

    This only works because Passport does not use body data to authenticate the user: it uses sessions that are not in the body. So you can use Passport and get user data, but you can't, for instance, be sure you have all non-file fields parsed before start downloading the file (since they come all together in express req stream)

提交回复
热议问题