0

To prevent spamming of my app I was thinking of logging how many times a given Ip makes a connection, like refreshing the page or what ever, so if they exceed the amount of connections per say a second or a minute, I can log their ip, how could I achieve this in either Express or socket.io?

1 Answers1

0

This answer details how to get the request IP. You'll need to build out some middleware that will keep track of how many times a particular IP has requested your server.

Here's a rough in-memory approach

var ips = {};

app.enable('trust proxy')
app.use(function(req, res, next) {

    if (ips[req.ip]) {
        var tracker = ips[req.ip];

        // If they've accessed less than a minute ago the same route increase count
        if (req.route === tracker.lastRoute && (new Date() - tracker.initReqTimestamp) < 60000) 
            tracker.count++;
        else { // Reset the counter
            tracker.count = 1
            tracker.initReqTimestamp = new Date();
            tracker.lastRoute = req.route;
        }

        ips[req.ip] = tracker;
    }
    else {
      ips[req.ip] = { 
        count: 1, 
        initReqTimestamp: new Date(),
        lastRoute: req.route
      };
    }

  if (ips[req.ip].count > connThreshold)
    // Do something

  else 
    return next(); // Continue to routes
});

// Put your Express Routes below this

As far as Socket.io, this answer details how to capture the socket client's IP. You can also write socket.io middleware to keep track of how many connections an IP has made using a similar approach to the Express middleware example above.

Community
  • 1
  • 1
peteb
  • 15,387
  • 7
  • 44
  • 55