Skip to content

Commit

Permalink
refact(server): move protectJSON middleware into its own file
Browse files Browse the repository at this point in the history
  • Loading branch information
petebacondarwin committed Mar 12, 2013
1 parent 0bce177 commit 8166a7a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 23 deletions.
23 changes: 23 additions & 0 deletions server/lib/protectJSON.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// JSON vulnerability protection
// we prepend the data with ")]},\n", which will be stripped by $http in AngularJS
module.exports = function(req, res, next) {
var _send = res.send;
res.send = function(body) {
var contentType = res.getHeader('Content-Type');
if ( contentType && contentType.indexOf('application/json') !== -1 ) {
if (2 == arguments.length) {
// res.send(body, status) backwards compat
if ('number' != typeof body && 'number' == typeof arguments[1]) {
this.statusCode = arguments[1];
} else {
this.statusCode = body;
body = arguments[1];
}
}
body = ")]}',\n" + body;
return _send.call(res, body);
}
_send.apply(res, arguments);
};
next();
};
25 changes: 2 additions & 23 deletions server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ var config = require('./config.js');
var passport = require('passport');
var security = require('./lib/security');
var xsrf = require('./lib/xsrf');
var protectJSON = require('./lib/protectJSON');
require('express-namespace');

var app = express();
Expand All @@ -27,29 +28,7 @@ app.use(config.server.staticUrl, function(req, res, next) {
res.send(404); // If we get here then the request for a static file is invalid
});

// JSON vulnerability protection
// we prepend the data with ")]},\n", which will be stripped by $http in AngularJS
app.use(function(req, res, next) {
var _send = res.send;
res.send = function(body) {
var contentType = res.getHeader('Content-Type');
if ( contentType && contentType.indexOf('application/json') !== -1 ) {
if (2 == arguments.length) {
// res.send(body, status) backwards compat
if ('number' != typeof body && 'number' == typeof arguments[1]) {
this.statusCode = arguments[1];
} else {
this.statusCode = body;
body = arguments[1];
}
}
body = ")]}',\n" + body;
return _send.call(res, body);
}
_send.apply(res, arguments);
};
next();
});
app.use(protectJSON);

app.use(express.logger()); // Log requests to the console
app.use(express.bodyParser()); // Extract the data from the body of the request - this is needed by the LocalStrategy authenticate method
Expand Down

0 comments on commit 8166a7a

Please sign in to comment.