44 lines
1003 B
JavaScript
Raw Normal View History

'use strict';
const utils = require('@strapi/utils');
const { has, toLower } = require('lodash/fp');
const { RateLimitError } = utils.errors;
module.exports =
(config, { strapi }) =>
async (ctx, next) => {
2022-12-27 09:19:57 -07:00
let rateLimitConfig = strapi.config.get('admin.rateLimit');
2022-12-27 09:19:57 -07:00
if (!rateLimitConfig) {
rateLimitConfig = {
enabled: true,
};
}
2022-12-27 09:19:57 -07:00
if (!has('enabled', rateLimitConfig)) {
rateLimitConfig.enabled = true;
2022-12-27 08:20:38 -07:00
}
2022-12-27 09:19:57 -07:00
if (rateLimitConfig.enabled === true) {
const rateLimit = require('koa2-ratelimit').RateLimit;
const userEmail = toLower(ctx.request.body.email) || 'unknownEmail';
2022-12-27 08:20:38 -07:00
const loadConfig = {
interval: { min: 5 },
max: 5,
prefixKey: `${userEmail}:${ctx.request.path}:${ctx.request.ip}`,
handler() {
throw new RateLimitError();
},
2022-12-27 09:19:57 -07:00
...rateLimitConfig,
...config,
2022-12-27 08:20:38 -07:00
};
2022-12-27 09:19:57 -07:00
return rateLimit.middleware(loadConfig)(ctx, next);
}
return next();
};