Skip to content

Commit

Permalink
fix: removed ctx.state support due to getter issues
Browse files Browse the repository at this point in the history
  • Loading branch information
titanism committed Jul 2, 2022
1 parent 1a1d5cc commit d0586c1
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 21 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ npm install koa-csrf
if (![ 'GET', 'POST' ].includes(ctx.method))
return next();
if (ctx.method === 'GET') {
ctx.body = ctx.state.csrf;
ctx.body = ctx.csrf;
return;
}
ctx.body = 'OK';
Expand Down
19 changes: 6 additions & 13 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ function CSRF(opts = {}) {
};

return function (ctx, next) {
Object.defineProperty(ctx.state, 'csrf', {
Object.defineProperty(ctx, 'csrf', {
get() {
if (ctx.state._csrf) {
return ctx.state._csrf;
if (ctx._csrf) {
return ctx._csrf;
}

if (!ctx.session) {
Expand All @@ -26,21 +26,14 @@ function CSRF(opts = {}) {
ctx.session.secret = tokens.secretSync();
}

ctx.state._csrf = tokens.create(ctx.session.secret);

return ctx.state._csrf;
}
});
ctx._csrf = tokens.create(ctx.session.secret);

// backwards compatible
Object.defineProperty(ctx, 'csrf', {
get() {
return ctx.state.csrf;
return ctx._csrf;
}
});

Object.defineProperty(ctx.response, 'csrf', {
get: () => ctx.state.csrf
get: () => ctx.csrf
});

if (opts.excludedMethods.includes(ctx.method)) {
Expand Down
8 changes: 1 addition & 7 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,12 +94,6 @@ test('should not respect the _csrf querystring given disableQuery=true', async (
t.is(res2.text, 'Invalid CSRF token');
});

test('backwards compatible with ctx.csrf usage', async (t) => {
const res = await t.context.request.get('/?old=true');
t.is(res.status, 200);
t.regex(res.text, tokenRegExp);
});

function getApp(opts = {}) {
const app = new Koa();
app.keys = ['a', 'b'];
Expand All @@ -109,7 +103,7 @@ function getApp(opts = {}) {
app.use((ctx, next) => {
if (!['GET', 'POST'].includes(ctx.method)) return next();
if (ctx.method === 'GET') {
ctx.body = ctx.query.old ? ctx.csrf : ctx.state.csrf;
ctx.body = ctx.csrf;
return;
}

Expand Down

0 comments on commit d0586c1

Please sign in to comment.