假设我正确地使用了passport
,bcrypt
,express-sessions
和mysql
,则该代码应该将用户信息添加到会话中。我一生无法解决问题所在。
App.js
个文件
passport.use('local', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true //passback entire req to call back
}, function(req, email, password, done) {
connection.query("SELECT * FROM accounts WHERE email = ?", [email], async(err, rows, fields) => {
//if an error occurrs in mysql
if (err) {
return done(null, false)
connection.end()
}
//if there are no matching entries
if (!rows.length) {
console.log('invalid email')
return done(null, false)
connection.end()
}
//if the passwords don't compare
if (!(await bcrypt.compare(password, rows[0].password))) {
console.log('incorrect password')
done(null, false)
connection.end()
}
//if none of that happens
req.session.user = rows[0]
console.log('logged in')
connection.end()
});
}));
//handles de/serialization of the user data (all integrated from passport docs)
passport.serializeUser(function(user, done) {
return done(null, user.id)
console.log(user.id + "serialized")
});
passport.deserializeUser(function(id, done) {
connection.query("SELECT * FROM accounts WHERE id = " + id, function(err, rows) {
console.log('done' + rows[0])
return done(err, rows[0])
});
});
验证路线代码
router.post('/auth', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/account'
}));
该代码将用户登录,并登录到console
,然后再次将他们注销,并重定向到/account
。我不知道身份验证出了什么问题,谢谢您提前的答复!
答案 0 :(得分:0)
您可以使用express-session实现相同的目的。
npm i express-session --save
var session = require('express-session');
app.use(session({ secret: "YourSecretKeyGoesHere", saveUninitialized: true, resave: true }));
然后检查您的会话。