2022-10-05 08:21:34 -07:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
const utils = require('@strapi/utils');
|
2022-12-20 08:03:33 -07:00
|
|
|
const { has, toLower } = require('lodash/fp');
|
2022-10-05 08:21:34 -07:00
|
|
|
|
|
|
|
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-16 10:42:28 -07:00
|
|
|
|
2022-12-27 09:19:57 -07:00
|
|
|
if (!rateLimitConfig) {
|
|
|
|
rateLimitConfig = {
|
2022-12-16 10:42:28 -07:00
|
|
|
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;
|
2022-12-16 10:42:28 -07:00
|
|
|
|
|
|
|
const userEmail = toLower(ctx.request.body.email) || 'unknownEmail';
|
|
|
|
|
2022-12-27 08:20:38 -07:00
|
|
|
const loadConfig = {
|
2022-12-16 10:42:28 -07:00
|
|
|
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,
|
2022-12-16 10:42:28 -07:00
|
|
|
...config,
|
2022-12-27 08:20:38 -07:00
|
|
|
};
|
|
|
|
|
2022-12-27 09:19:57 -07:00
|
|
|
return rateLimit.middleware(loadConfig)(ctx, next);
|
2022-12-16 10:42:28 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
return next();
|
2022-10-05 08:21:34 -07:00
|
|
|
};
|