[英]passport.js authentication and error handling
I have an API that authenticates a user from a mobile app. 我有一个API,可以通过移动应用验证用户身份。 I'm running in to an issue where if a user logs in to the app with the wrong password or an invalid username then the node app crashes due to an authentication error being thrown, is there a way to have handle authentication errors in passport without crashing the api?
我遇到一个问题,如果用户使用错误的密码或无效的用户名登录应用程序,则节点应用程序会由于抛出身份验证错误而崩溃,是否有办法在没有护照的情况下处理护照中的身份验证错误使API崩溃?
var mysql = require('mysql');
var bcrypt = require('bcrypt-nodejs');
var dbconfig = require('./database');
var connection = mysql.createConnection(dbconfig.connection);
connection.query('USE ' + dbconfig.database);
module.exports = function(passport) {
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
connection.query("SELECT * FROM saf_users WHERE id = ? ",[id], function(err, rows){
done(err, rows[0]);
});
});
passport.use(
'local-login',
new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'username',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, username, password, done) { // callback with email and password from our form
connection.query("SELECT * FROM saf_users WHERE username = ?",[username], function(err, rows){
let bcryptedPwd = rows[0].password;
let newPwd = bcryptedPwd.replace(bcryptedPwd.charAt(2), "a");
if (err)
return done(err);
if (!rows.length) {
//return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
return res.status(401).json({ message: 'Unauthorized user!' });
}
if (!bcrypt.compareSync(password, newPwd))
//return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
return res.status(401).json({ message: 'Unauthorized user!' });
// all is well, return successful user
return done(null, rows[0]);
});
})
);
};
return res.status(401).json({ message: 'Unauthorized user!' });
you should rather do the following 您应该执行以下操作
return done({message: 'Unauthorized user!'});
basically the first argument in your done()
callback takes the error. 基本上,
done()
回调中的第一个参数会产生错误。 So you can return message to your user and not break your app. 因此,您可以向用户返回消息,而不会破坏您的应用程序。 as @robertklep said, res isn't defined.
正如@robertklep所说,res未定义。 But this is the best way to handle errors.
但这是处理错误的最佳方法。 You can check out this Example Here
您可以在此处查看此示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.