2020-10-27 11:27:17 +01:00
|
|
|
'use strict';
|
|
|
|
|
2023-07-17 14:55:45 -07:00
|
|
|
const utils = require('@strapi/utils');
|
|
|
|
const { has, toLower } = require('lodash/fp');
|
|
|
|
|
|
|
|
const { RateLimitError } = utils.errors;
|
|
|
|
|
2022-08-08 23:33:39 +02:00
|
|
|
module.exports =
|
|
|
|
(config, { strapi }) =>
|
|
|
|
async (ctx, next) => {
|
2023-07-17 14:55:45 -07:00
|
|
|
let rateLimitConfig = strapi.config.get('plugin.users-permissions.ratelimit');
|
|
|
|
|
|
|
|
if (!rateLimitConfig) {
|
|
|
|
rateLimitConfig = {
|
|
|
|
enabled: true,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!has('enabled', rateLimitConfig)) {
|
|
|
|
rateLimitConfig.enabled = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (rateLimitConfig.enabled === true) {
|
|
|
|
const rateLimit = require('koa2-ratelimit').RateLimit;
|
|
|
|
|
|
|
|
const userIdentifier = toLower(ctx.request.body.email) || 'unknownIdentifier';
|
2023-07-19 01:25:04 -07:00
|
|
|
let requestPath = toLower(ctx.request.path) || 'unknownPath';
|
|
|
|
|
|
|
|
if (requestPath.endsWith('/')) {
|
|
|
|
if (requestPath !== '/') {
|
|
|
|
requestPath = requestPath.slice(0, -1);
|
|
|
|
}
|
|
|
|
}
|
2023-07-17 14:55:45 -07:00
|
|
|
|
|
|
|
const loadConfig = {
|
|
|
|
interval: { min: 5 },
|
|
|
|
max: 5,
|
|
|
|
prefixKey: `${userIdentifier}:${requestPath}:${ctx.request.ip}`,
|
|
|
|
handler() {
|
|
|
|
throw new RateLimitError();
|
|
|
|
},
|
|
|
|
...rateLimitConfig,
|
|
|
|
...config,
|
|
|
|
};
|
|
|
|
|
|
|
|
return rateLimit.middleware(loadConfig)(ctx, next);
|
|
|
|
}
|
|
|
|
|
|
|
|
return next();
|
2022-08-08 23:33:39 +02:00
|
|
|
};
|