错误:无法将用户序列化到会话中



我使用的是带有nodejs的mysql。我得到了";错误:未能将用户序列化到会话中;。当我在serializuser函数中console.log user时;serialize[object object]";并且在";本地登录";策略,它打印RowDataPacket,如下所示。

RowDataPacket {
Patient_id: 2,
fname: 'xxx',
mname: 'yyy',
lname: 'zzz',
Email: 'xxx@yyy.com',
pass: '$2b$10$ycZI4SLTJEihxKDHpCXwcOhkmBiOKzmMqFyuEOgXa0KuXYupgaMeG',
Contact: '090078601',
Gender: 'Male',
dateofbirth: 1111-01-13T19:31:48.000Z,
Blood_group: null
}

// used to serialize the user for the session
passport.serializeUser(function(user, done) {
console.log(`serialize ${user}`)
done(null, user.patient_id)
})
// used to deserialize the user
passport.deserializeUser(function(id, done) {
// connection.connect()
connection.query("SELECT * FROM PATIENT WHERE PATIENT_ID = ? ",[id], function(err, rows){
done(err, rows[0])
})
// connection.end()
})

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.connect()
connection.query("SELECT * FROM PATIENT WHERE EMAIL = ?",[email],function(err,rows){
if (err)
return done(err)
if (!rows.length) {
return done(null, false, req.flash('error', 'No user found.')) // req.flash is the way to set flashdata using connect-flash
} 
bcrypt.compare(password, rows[0].pass, function(err, result) {
if(!result)
{
return done(null, false, req.flash('error', 'Oops! Wrong password.'))
}
// console.log(rows[0])
});
return done(null, rows[0])
})
// connection.end()
}
))

我的后登录看起来像这个

router.post('/patient/login',  ensureGuest, passport.authenticate('local-login', {
successRedirect : '/home', // redirect to the secure profile section
failureRedirect : 'login', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
})
);

不要建议使用会话:在后方法中进行身份验证时为false

sql查询返回的对象类型导致了问题,序列化和反序列化接受json对象,所以我只是在连接配置中添加了stringifyObjects选项,这样sql查询返回json对象而不是通常返回的默认对象类型。

module.exports = {
'connection': {
'host': 'localhost',
'user': 'root',
'password': 'fast',
'database': 'hms',
'stringifyObjects': 'Stringify' 
}
};

最新更新