I have a system to upload files with node.js, express and multer, the files are stored inside a static directory. what I want is for them to be stored on the server and be able to see them only if I have logged in.
Issue:
my system to upload is fine, but I need to protect the files in a directory /files/documents/hv.pdf, as the browser saves history whenever I enter the url the file is opened, something that should not happen, how can I avoid access to if the user has not logged in?
I was trying with a Middleware that runs if the url's string bears the name of the / files folder, it's funny that if I do not put the file name or put another name like /files/document/test.txt it works but not When I visited the link in the static folder, I thought it was the cache but it's definitely not that
this Middleware
module.exports = (req,res,next)=>{
    let regex = /^\/files\/.*$/;
    if (!regex.test(req.url)) { return next(); }
    // for test
    req.session.user = {name:"thaylor"}; //comment for not session
    //fin for test
    if(req.session.user){
        next();
    }else{
        res.end('You are not allowed!');
    }
}
Update, this solution 2018-04-2017
Middleware for get root path and protected route app.js
const protectedfile = require("./controllers/protectedfile");
app.use(function(req, res, next) {
    req.rootPath = __dirname;
    next();
});
app.use('/files', protectedfile);
app.use('/files', express.static(path.join(__dirname, 'files')) );
this file controllers/protectedfile.js
const path = require('path'); 
module.exports = (req,res,next)=>{
    if(!req.session.user){
        res.send("Route protected");
    }else{          
        let file = path.join(req.rootPath, req.originalUrl);  
        res.download(file, function (err) {
            if (err) {
                console.log("Error");
                console.log(err);
            } else {
                console.log("success"); 
            }        
        });       
    }
}
 
     
    