0
我使用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
感谢,您的实现看起来那么多比我好,我就用它作为指导试图解决的一塌糊涂我已经完成) – snowfinch27
欢迎您使用广泛使用的身份验证库[passportJs](http://passportjs.org/),它支持许多Oauth策略,如Google,Facebook等。对于mongoDb,有一个[mongoose](http://mongoosejs.com/)库,它有更多的功能,比如创建模式,预先保存钩子等。 –
谢谢,绝对会检查出来 – snowfinch27