mirror of
https://github.com/koajs/examples.git
synced 2026-01-25 14:48:15 +00:00
refactor csrf example
This commit is contained in:
parent
93fcb598d3
commit
6d0c74a06e
36
csrf/app.js
36
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
|
||||
*/
|
||||
|
||||
@ -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",
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user