How do I authenticate access to assets folder in s

2019-02-19 22:29发布

问题:

I am already using passport to authenticate users. I added kibana 3 to the assets folder and want users to access it only if they are authenticated. how do i do this ?

回答1:

The assets folder is intended for publicly-available files, like your images and Javascripts. If you want to protect those files, you can either override the default www middleware in Sails, which activates the Express static handler to servet those files (see details on overriding default middleware in this answer), or save the files you want to protect in a different location and use a controller action to serve them (probably the more reasonable option).

So, you could save the files in protected_files, and add a route like this to config/routes.js:

'/protected/:file': 'ProtectedFileController.download'

then in controllers/ProtectedFileController:

var fs = require('fs');
var path = require('path');
module.exports = {
    download: function(req, res) {

        // Get the URL of the file to download
        var file = req.param('file');

        // Get the file path of the file on disk
        var filePath = path.resolve(sails.config.appPath, "protected_files", file);

        // Should check that it exists here, but for demo purposes, assume it does
        // and just pipe a read stream to the response.
        fs.createReadStream(filePath).pipe(res);

    }


};

Then protect that controller / action using a policy like you would with any other area that needs authentication.