From 6d0c74a06eb5a7fa86c2e7ca91dac3a3d7333ce9 Mon Sep 17 00:00:00 2001 From: dead_horse Date: Mon, 7 Apr 2014 02:19:30 +0800 Subject: [PATCH] refactor csrf example --- csrf/app.js | 36 ++++++++++++------------------------ package.json | 2 +- 2 files changed, 13 insertions(+), 25 deletions(-) diff --git a/csrf/app.js b/csrf/app.js index 8491626..6aba701 100644 --- a/csrf/app.js +++ b/csrf/app.js @@ -6,43 +6,31 @@ var route = require('koa-route'); var app = module.exports = koa(); -/** - * csrf middleware - */ - -csrf(app); - /** * csrf need session */ + app.keys = ['session key', 'csrf example']; app.use(session()); /** - * assert CSRF token + * maybe a bodyparser */ -app.use(function* (next) { - if (this.method === 'GET' - || this.method === 'HEAD' - || this.method === 'OPTIONS') { - return yield* next; - } - - // co-body or use other bodyparser middlewares - var body = yield parse(this); - try { - this.assertCSRF(body); - } catch (err) { - this.status = 403; - this.body = { - message: 'This CSRF token is invalid!' - }; - return; +app.use(function *(next) { + if (this.is('application/json')) { + this.request.body = yield parse(this); } yield* next; }); +/** + * csrf middleware + */ + +app.use(csrf()); + + /** * route */ diff --git a/package.json b/package.json index 4244ec3..1e7fb60 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,7 @@ "koa": "^0.5.0", "koa-basic-auth": "^1.1.1", "koa-compose": "^2.1.0", - "koa-csrf": "^1.0.1", + "koa-csrf": "^1.1.0", "koa-logger": "^1.1.0", "koa-route": "^1.0.2", "koa-session": "^1.2.0",