Format remaining time

main
Ashelyn Dawn 4 years ago
parent 1289b56b2b
commit 1cafdf776b

@ -1,4 +1,5 @@
const {RateLimiterPostgres, RateLimiterUnion} = require('rate-limiter-flexible');
const {Duration} = require('luxon')
const pg = require('../../db/pg')
const globalOptions = {
@ -32,19 +33,31 @@ const loginRateLimitPool = new RateLimiterUnion(...loginRateLimits)
module.exports.loginRateLimit = async (req, res) => {
try {
let currentLimits = await Promise.all(
loginRateLimits.map(limiter => limiter.get(req.body.email))
)
const failed = currentLimits.filter(limit => limit?.remainingPoints === 0)
if(failed.length > 0)
throw failed;
await loginRateLimitPool.consume(req.body.email)
return 'next';
} catch (limits) {
const wait = Math.max(...Object.values(limits).map(limit => limit?.msBeforeNext || 1));
const waitMillis = Math.max(...Object.values(limits).map(limit => limit?.msBeforeNext || 1));
const wait = Math.ceil(waitMillis / 1000)
res.status(429)
res.set({
'Retry-After': Math.ceil(wait / 1000)
'Retry-After': wait
})
const duration = secondsToTimeString(wait)
res.json({errors: [{
param: 'email',
msg: `Too many password attempts, please wait ${Math.ceil(wait / 1000)} seconds`
msg: `Too many login attempts, please wait ${duration}`
},{
param: 'password',
msg: ' '
@ -56,4 +69,32 @@ module.exports.loginRateLimit.reset = email => Promise.all(
loginRateLimits.map(rateLimit =>
rateLimit.delete(email)
)
)
)
function secondsToTimeString(seconds) {
const duration = Duration.fromObject({seconds}).shiftTo('days', 'hours', 'minutes', 'seconds')
let string = '';
if(duration.days)
string += `${duration.days} day${duration.days > 1 ? 's' : ''}`
if(duration.hours) {
if (string) string += ', '
string += `${duration.hours} hour${duration.hours > 1 ? 's' : ''}`
}
if(duration.minutes) {
if (string) string += ', '
string += `${duration.minutes} minute${duration.minutes > 1 ? 's' : ''}`
}
if(duration.seconds) {
if (string) string += ', '
string += `${duration.seconds} second${duration.seconds > 1 ? 's' : ''}`
}
if(!string)
return '1 second'
return string
}
Loading…
Cancel
Save