refactor csrf example

This commit is contained in:
dead_horse 2014-04-07 02:19:30 +08:00
parent 93fcb598d3
commit 6d0c74a06e
2 changed files with 13 additions and 25 deletions

View File

@ -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
*/

View File

@ -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",