Feature/delay middleware (#146)

* add delay middleware to login and signin routes

* Different delay for sendStatus and json

---------

Co-authored-by: Markus Frindt <m.frindt@cognigy.com>
This commit is contained in:
Markus Frindt
2023-04-06 14:25:45 +02:00
committed by GitHub
parent 84305e30cc
commit 009396becc
2 changed files with 34 additions and 0 deletions

2
app.js
View File

@@ -64,6 +64,7 @@ const {
}, logger);
const PORT = process.env.HTTP_PORT || 3000;
const authStrategy = require('./lib/auth')(logger, retrieveKey);
const {delayLoginMiddleware} = require('./lib/middleware');
passport.use(authStrategy);
@@ -129,6 +130,7 @@ app.use(nocache());
app.use(passport.initialize());
app.use(cors());
app.use(express.urlencoded({extended: true}));
app.use(delayLoginMiddleware);
app.use(unless(['/stripe'], express.json()));
app.use('/v1', unless(
[

32
lib/middleware.js Normal file
View File

@@ -0,0 +1,32 @@
const logger = require('./logger');
function delayLoginMiddleware(req, res, next) {
if (req.path.includes('/login') || req.path.includes('/signin')) {
const min = 200;
const max = 1000;
/* Random delay between 200 - 1000ms */
const sendStatusDelay = Math.floor(Math.random() * (max - min + 1)) + min;
/* the res.json take longer, we decrease the max delay slightly to 0-800ms */
const jsonDelay = Math.floor(Math.random() * 800);
logger.debug(`delayLoginMiddleware: sendStatus ${sendStatusDelay} - json ${jsonDelay}`);
const sendStatus = res.sendStatus;
const json = res.json;
res.sendStatus = function(status) {
setTimeout(() => {
sendStatus.call(res, status);
}, sendStatusDelay);
};
res.json = function(body) {
setTimeout(() => {
json.call(res, body);
}, jsonDelay);
};
}
next();
}
module.exports = {
delayLoginMiddleware
};