【发布时间】:2016-08-05 05:36:52
【问题描述】:
我正在使用 ExpressJS 中间件检查数据库中的用户 ip,如果过去一小时内登录失败超过 7 次,则停止响应用户,如果一切正常,我在数据库连接之前使用检查“/”以不向数据库发送垃圾邮件。但事实证明,当中间件访问数据库并检查回调时,第一个 else 中的代码会运行。这是我的中间件:
// check for failed logins from this ip in db
// if allowed number exceeded - stop responding
app.use(function (req, res, next) {
if(req._parsedUrl.pathname === '/') {
MongoClient.connect(databaseUri || 'mongodb://localhost:27017/dev', function (err, db) {
assert.equal(err, null);
var failedLogins = db.collection('FailedLogins');
failedLogins.find({ip: req._remoteAddress}).toArray(function (err, results) {
assert.equal(err, null);
console.log('db check');
// if ip is in FailedLogins collection
if (results.length) {
// if there are more than 7 logins and they haven't expired
if (results[0].failedLoginsNum >= 7 && parseInt(results[0].expiration) >= parseInt(Date.now())) {
res.end();
} else {
next();
}
} else {
next();
}
});
});
} else {
console.log('next');
next();
}
});
这是控制台输出:
db check
GET / 200 20.117 ms - -
next
GET /favicon.ico 200 207.559 ms - 1353
【问题讨论】: