Skip to content

Commit

Permalink
refact(server): refactor the xsrf function to be cleaner for the book
Browse files Browse the repository at this point in the history
  • Loading branch information
petebacondarwin committed Mar 7, 2013
1 parent eeb4eea commit 71af642
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions server/lib/xsrf.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,22 @@ function uid(len) {
module.exports = function(req, res, next) {
// Generate XSRF token
var token = req.session._csrf || (req.session._csrf = uid(24));
// Get the token in the current request
var requestToken = req.headers['x-xsrf-token'];
// Add it to the cookie
res.cookie('XSRF-TOKEN', token);

// Ignore if it is just a read-only request
if ('GET' === req.method || 'HEAD' === req.method || 'OPTIONS' === req.method) {
return next();
}

// Check the token in the request against the one stored in the session
var requestToken = req.headers['x-xsrf-token'];
if ( requestToken !== token ) {
return res.send(403);
switch(req.method) {
case 'GET':
case 'HEAD':
case 'OPTIONS':
break;
default:
// Check the token in the request against the one stored in the session
if ( requestToken !== token ) {
return res.send(403);
}
}
// All is OK, continue as you were.
return next();
Expand Down

0 comments on commit 71af642

Please sign in to comment.