N
N
nosok122020-02-07 09:10:08
Node.js
nosok12, 2020-02-07 09:10:08

How to handle concurrent requests from the same user in NodeJS?

For example:

app.post('/login', (req, res) => {
// I want to check.
// If we are already authenticating this user from the given IP(or fingerprint).
// then res.send ('Authentication already in progress');
});

I'm interested in how to properly process the request at such moments. I am reading "Secure your NodeJS WEB application - Karl Duuna". He gives this example:

// Map our authentications
var inProgress = {};
app.post('/login', function (req, res, next) {
var key = req.ip + ':' + req.body.username;
// check if we are already authenticating this user from the given IP
if (inProgress[key]) {
req.session.error = 'Authentication already in progress';
redirect('/');
return;
}
inProgress[key] = true;
Etc.

But of course, it is not advised to store inProgress in the application's memory.
Then is it possible, for example, to make a separate collection in mongodb that will store documents of the form:
inProgress: true,
fingerprint: some_string_id

And write (pseudocode) in the code:

app.post('/login', async (req, res) => {
/ / If the authentication request has already been and has not yet been processed, redirect
// based on, for example, fingerprint
if(in_progress(fingerprint)){
res.redirect('/login', { errors: ['Authentication already in progress'] } );
return;
}
// If no one made any requests for authentication in parallel
// add the in_progress document to mongodb
// after processing the request, be sure to delete it from the database
in_progress[inProgress] = true;
in_progress[fingerprint] = some_string_id;

Or is it all too sophisticated and there will be a big load on the server and database? Or maybe you don't need to do this in NodeJS at all? But if you don't, why does a fairly popular book (on the topic of secure and NodeJS) say that we should handle such parallel requests?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2020-02-07
@nosok12

not too sophisticated, instead of mongo you can take something more suitable, for example redis. the load will be small, no more than going to the database for data for a query in a normal scenario.
But the main question that you should find in the book is why do it at all, what problem is it designed to cope with. Then see if it is relevant for you and if it is worth the effort.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question