我的快递应用程序使用以下基本身份验证功能:
exports.basicAuth = express.basicAuth(function (user, pass, callback) {
findUserByEmail(user, function (err, account) {
var isPasswordMatch = false;
log.info("Authenticate request user-pass: " + user + ":" + pass);
if (err) {
log.info("Error occurred when authenticate user: " + err);
}
if (account == null || account == undefined) {
log.info("Account not found");
} else {
if (!isActive(account)) {
log.info("Account is not active");
}
if (account.password != encryptPassword(account.salt, pass)) {
log.info("Wrong pass");
isPasswordMatch = false;
} else {
isPasswordMatch = true;
}
}
var authenticated = err == null && account != null && account != undefined && isActive(account) && isPasswordMatch;
callback(null, authenticated);
});
});
有时,当服务器过载时,findUserByEmail
请求将失败。在这种情况下,上述函数会导致服务器返回401错误。相反,我想返回一个5XX错误代码,以便客户端知道服务器上存在问题,而不一定是他们传递的凭据。在findUserByEmail中返回5XX错误代码而不是401错误的最佳方法是什么?
答案 0 :(得分:0)
我找到了解决方案。我只是将身份验证处理程序包装在标准请求处理程序中,并在出现问题时发送错误响应。
exports.basicAuth = function(req, res, next) {
express.basicAuth(function (user, pass, callback) {
findUserByEmail(user, function (err, account) {
var isPasswordMatch = false;
log.info("Authenticate request user-pass: " + user + ":" + pass);
if (err) {
log.info("Error occurred when authenticate user");
res.send(500, { error: 'Unable to authenticate request' });
return;
}
...
});
})(req, res, next);
};