Skip to content

Commit

Permalink
feat: removed invalidTokenMessage and invalidTokenStatusCode, added e…
Browse files Browse the repository at this point in the history
…rrorHandler function option
  • Loading branch information
titanism committed Jul 2, 2022
1 parent db4df33 commit 495bf75
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 15 deletions.
7 changes: 2 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

> CSRF tokens for Koa
> **NOTE:** As of v5.0.0+ `ctx.csrf`, `ctx_csrf`, and `ctx.response.csrf` are removed – instead use `ctx.state._csrf`
> **NOTE:** As of v5.0.0+ `ctx.csrf`, `ctx_csrf`, and `ctx.response.csrf` are removed – instead use `ctx.state._csrf`. Furthermore we have dropped `invalidTokenMessage` and `invalidTokenStatusCode` in favor of an `errorHandler` function option.

## Table of Contents
Expand Down Expand Up @@ -100,8 +100,7 @@ npm install koa-csrf

## Options

* `invalidTokenMessage` (String or Function) - defaults to `Invalid CSRF token`, but can also be a function that accepts one argument `ctx` (useful for i18n translation, e.g. using `ctx.request.t('some message')` via [@ladjs/i18n][]
* `invalidTokenStatusCode` (Number) - defaults to `403`
* `errorHandler` (Function) - defaults to a function that returns `ctx.throw(403, 'Invalid CSRF token')`
* `excludedMethods` (Array) - defaults to `[ 'GET', 'HEAD', 'OPTIONS' ]`
* `disableQuery` (Boolean) - defaults to `false`
* `ignoredPathGlobs` (Array) - defaults to an empty Array, but you can pass an Array of glob paths to ignore
Expand All @@ -122,6 +121,4 @@ npm install koa-csrf

##

[@ladjs/i18n]: https://github.com/ladjs/i18n

[npm]: https://www.npmjs.com/
15 changes: 5 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ function CSRF(opts = {}) {
const tokens = csrf(opts);

opts = {
invalidTokenMessage: 'Invalid CSRF token',
invalidTokenStatusCode: 403,
errorHandler(ctx) {
return ctx.throw(403, 'Invalid CSRF token');
},
excludedMethods: ['GET', 'HEAD', 'OPTIONS'],
disableQuery: false,
ignoredPathGlobs: [],
Expand Down Expand Up @@ -50,14 +51,8 @@ function CSRF(opts = {}) {
ctx.get('x-csrf-token') ||
ctx.get('x-xsrf-token');

if (!token || !tokens.verify(ctx.session.secret, token)) {
return ctx.throw(
opts.invalidTokenStatusCode,
typeof opts.invalidTokenMessage === 'function'
? opts.invalidTokenMessage(ctx)
: opts.invalidTokenMessage
);
}
if (!token || !tokens.verify(ctx.session.secret, token))
return opts.errorHandler(ctx);

return next();
};
Expand Down

0 comments on commit 495bf75

Please sign in to comment.