我正在尝试使用Node.js,Passport和MySQL创建身份验证。
这是我的本地登录策略:
passport.use('local-login', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) { // callback with email and password from our form
connection.query("SELECT * FROM `users` WHERE `email` = '" + email + "'", function(err, rows) {
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
}
console.log(`Email found ${email}`)
bcrypt.compare(password, rows[0].Password, function(err, res) {
if (res) {
//Password matched
console.log('Password matched')
// all is well, return successful user
return done(null, rows[0]);
} else {
//password did not match
console.log('Password did not match')
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
}
})
})
}));
我收到控制台消息,提示“密码匹配”,但看起来像
return done(null,rows[0])
抛出错误消息。我登录的帖子路线是
router.post("/login",passport.authenticate('local-login'),function(req,res){
res.redirect("/users")
})
我还将按照护照文件进行序列化和反序列化:
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
connection.query("select * from users where id = " + id, function(err, rows) {
done(err, rows[0]);
});
});
这是我的护照初始化和护照会话代码
app.use(require("express-session")({
secret:"willsecurelater",
resave:false,
saveUninitialized:false
}));
app.use(passport.initialize());
app.use(passport.session())