csrf.js 1013 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. 'use strict';
  2. const debug = require('debug')('egg-security:csrf');
  3. const typeis = require('type-is');
  4. const utils = require('../utils');
  5. module.exports = options => {
  6. return function csrf(ctx, next) {
  7. if (utils.checkIfIgnore(options, ctx)) {
  8. return next();
  9. }
  10. // ensure csrf token exists
  11. if ([ 'any', 'all', 'ctoken' ].includes(options.type)) {
  12. ctx.ensureCsrfSecret();
  13. }
  14. // supported requests
  15. const method = ctx.method;
  16. let isSupported = false;
  17. for (const eachRule of options.supportedRequests) {
  18. if (eachRule.path.test(ctx.path)) {
  19. if (eachRule.methods.includes(method)) {
  20. isSupported = true;
  21. break;
  22. }
  23. }
  24. }
  25. if (!isSupported) {
  26. return next();
  27. }
  28. if (options.ignoreJSON && typeis.is(ctx.get('content-type'), 'json')) {
  29. return next();
  30. }
  31. const body = ctx.request.body || {};
  32. debug('%s %s, got %j', ctx.method, ctx.url, body);
  33. ctx.assertCsrf();
  34. return next();
  35. };
  36. };