Skip to content

Instantly share code, notes, and snippets.

@chadxz
Last active January 4, 2016 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chadxz/8661772 to your computer and use it in GitHub Desktop.
Save chadxz/8661772 to your computer and use it in GitHub Desktop.
protecting static assets in sails.js

With these files in place, and given you had a static file at assets/protected/hello.txt with the words 'hello world' in it, and another file at assets/robots.txt, you could do sails lift and do a GET on http://localhost:1337/robots.txt and have the file returned normally, but do a GET on http://localhost:1337/protected/hello.txt and you would get 'you are not allowed!'.

You can extend this example to do things like HTTP basic authentication, filtering based on origin, etc.

This gist is inspired by this stackoverflow link

// config/express.js
"use strict";
var staticguard = require('../lib/middleware/staticguard');
exports.express = {
customMiddleware: function (app) {
app.use(staticguard(/^\/protected\/.*$/));
}
}
// lib/middleware/staticguard.js
"use strict";
module.exports = function (regex) {
return function (req, res, next) {
if (!regex.test(req.url)) {
return next();
}
res.end('you are not allowed!');
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment