-
-
Notifications
You must be signed in to change notification settings - Fork 7.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Update both Admin and U&P ratelimit to lower path
- Loading branch information
1 parent
5b675cc
commit ed364d9
Showing
2 changed files
with
40 additions
and
22 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
59 changes: 38 additions & 21 deletions
59
packages/plugins/users-permissions/server/middlewares/rateLimit.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,44 @@ | ||
'use strict'; | ||
|
||
const utils = require('@strapi/utils'); | ||
const { has, toLower } = require('lodash/fp'); | ||
|
||
const { RateLimitError } = utils.errors; | ||
|
||
module.exports = | ||
(config, { strapi }) => | ||
async (ctx, next) => { | ||
const ratelimit = require('koa2-ratelimit').RateLimit; | ||
|
||
const message = [ | ||
{ | ||
messages: [ | ||
{ | ||
id: 'Auth.form.error.ratelimit', | ||
message: 'Too many attempts, please try again in a minute.', | ||
}, | ||
], | ||
}, | ||
]; | ||
|
||
return ratelimit.middleware({ | ||
interval: 1 * 60 * 1000, | ||
max: 5, | ||
prefixKey: `${ctx.request.path}:${ctx.request.ip}`, | ||
message, | ||
...strapi.config.get('plugin.users-permissions.ratelimit'), | ||
...config, | ||
})(ctx, next); | ||
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'; | ||
const requestPath = toLower(ctx.request.path) || 'unknownPath'; | ||
|
||
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(); | ||
}; |