Skip to content
This repository has been archived by the owner on Sep 14, 2022. It is now read-only.

Commit

Permalink
Merge 9c01f13 into 4303657
Browse files Browse the repository at this point in the history
  • Loading branch information
STRML committed Aug 24, 2014
2 parents 4303657 + 9c01f13 commit 5ca5c1f
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 4 deletions.
10 changes: 7 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
var Cookie = require('cookie');
var csrfTokens = require('csrf');
var sign = require('cookie-signature').sign;
var extend = require('extend');

/**
* CSRF protection middleware.
Expand All @@ -26,7 +27,7 @@ var sign = require('cookie-signature').sign;
* @api public
*/

var ignoreMethod = {
var ignoreMethodDefaults = {
GET: true,
HEAD: true,
OPTIONS: true,
Expand All @@ -46,6 +47,9 @@ module.exports = function csurf(options) {
options.cookie.key = '_csrf'
}

// Allow user to define HTTP methods to ignore
var ignoreMethod = extend({}, ignoreMethodDefaults, options && options.ignoreMethod)

return function csrf(req, res, next) {
var secret = getsecret(req, options.cookie)
var token
Expand Down Expand Up @@ -83,7 +87,7 @@ module.exports = function csurf(options) {
}

// verify the incoming token
verifytoken(req, tokens, secret, value(req))
verifytoken(req, tokens, secret, value(req), ignoreMethod)

next()
}
Expand Down Expand Up @@ -197,7 +201,7 @@ function setsecret(req, res, val, cookie) {
* @api private
*/

function verifytoken(req, tokens, secret, val) {
function verifytoken(req, tokens, secret, val, ignoreMethod) {
// ignore these methods
if (ignoreMethod[req.method]) {
return
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"dependencies": {
"cookie": "0.1.2",
"cookie-signature": "1.0.4",
"csrf": "~2.0.1"
"csrf": "~2.0.1",
"extend": "~1.3.0"
},
"devDependencies": {
"body-parser": "~1.5.2",
Expand Down
16 changes: 16 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,22 @@ describe('csurf', function () {
.expect(500, /cookieParser.*secret/, done)
});

it('should check GET when explicitly restricted', function(done) {
var server = createServer({ignoreMethod: {GET: false}});

request(server)
.get('/')
.expect(403, done);
});

it('should not check POST when explicitly allowed', function(done) {
var server = createServer({ignoreMethod: {POST: true}});

request(server)
.post('/')
.expect(200, done);
});

describe('req.csrfToken()', function () {
it('should return same token for each call', function (done) {
var app = connect()
Expand Down

0 comments on commit 5ca5c1f

Please sign in to comment.