我有这个函数来findOneAndUpdate,它会查找是否存在用户名然后设置时间字段并增加其他字段的数量。
function _lockIfFailedAttemptsReachLimit(username,next) {
colUser.findOneAndUpdate({ username }, { // increase failed attempt counter
$set: { failedLoginAt: new Date() },
$inc: { nFailedLogin: 1 },
}, { upsert: false, returnOriginal: false }, (err, result) => {
if (err) { // Undefined.
next('Undefined error!');
} else {
let foundUser = result.value;
if (_.isNil(foundUser)) { // cannot find username
//nothing here yet.
}
let nFailed = _.get(foundUser, 'nFailedLogin', 0);
let errMsg = `Invalid username or passsword. You have tried ${nFailed}/${MAX_FAILED_LOGIN_ATTEMPTS} login attempts`;
if (nFailed < MAX_FAILED_LOGIN_ATTEMPTS) {
next(errMsg);
} else {
_lockAccount(username, (err, result) => {
if (!err) {
errMsg += `. Your account has been locked for ${WAITING_TIME_AFTER_LOCKED} seconds.`;
}
next(errMsg);
});
}
}
});
}
现在我想要在同一个函数中如果找不到用户名,那么它会插入用户名值并为该用户名执行相同的过程。我怎么能在最有效的编码中做到这一点? 我试过了:
function _lockIfFailedAttemptsReachLimit(username, req, res, next) {
colUser.findOneAndUpdate({ username }, { // increase failed attempt counter
$set: { failedLoginAt: new Date() },
$inc: { nFailedLogin: 1 },
}, { upsert: false, returnOriginal: false }, (err, result) => {
if (err) { // Undefined.
next('Undefined error!');
} else {
let foundUser = result.value;
if (_.isNil(foundUser)) { // cannot find username
//I think can try to put the code here ?
let username = (req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress).split(",")[0];
// insert username to the table and call the function to continue from the beginning
}
let nFailed = _.get(foundUser, 'nFailedLogin', 0);
let errMsg = `Invalid username or passsword. You have tried ${nFailed}/${MAX_FAILED_LOGIN_ATTEMPTS} login attempts`;
if (nFailed < MAX_FAILED_LOGIN_ATTEMPTS) {
next(errMsg);
} else {
_lockAccount(username, (err, result) => {
if (!err) {
errMsg += `. Your account has been locked for ${WAITING_TIME_AFTER_LOCKED} seconds.`;
}
next(errMsg);
});
}
}
});
}