Preventing Brute Force Using Node and Express JS

前端 未结 6 1007
陌清茗
陌清茗 2021-02-05 18:42

I\'m building a website using Node and Express JS and would like to throttle invalid login attempts. Both to prevent online cracking and to reduce unnecessary database calls. Wh

6条回答
  •  别跟我提以往
    2021-02-05 18:57

    Maybe something like this might help you get started.

    var failures = {};
    
    function tryToLogin() {
        var f = failures[remoteIp];
        if (f && Date.now() < f.nextTry) {
            // Throttled. Can't try yet.
            return res.error();
        }
    
        // Otherwise do login
        ...
    }
    
    function onLoginFail() {
        var f = failures[remoteIp] = failures[remoteIp] || {count: 0, nextTry: new Date()};
        ++f.count;
        f.nextTry.setTime(Date.now() + 2000 * f.count); // Wait another two seconds for every failed attempt
    }
    
    function onLoginSuccess() { delete failures[remoteIp]; }
    
    // Clean up people that have given up
    var MINS10 = 600000, MINS30 = 3 * MINS10;
    setInterval(function() {
        for (var ip in failures) {
            if (Date.now() - failures[ip].nextTry > MINS10) {
                delete failures[ip];
            }
        }
    }, MINS30);
    

提交回复
热议问题