How do I authenticate access to assets folder in sails.js

你离开我真会死。 提交于 2019-12-01 09:42:34
sgress454

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!