Node.js登录身份验证系统无法正确存储用户

时间:2020-06-27 11:07:44

标签: javascript mysql node.js session passport.js

假设我正确地使用了passportbcryptexpress-sessionsmysql,则该代码应该将用户信息添加到会话中。我一生无法解决问题所在。 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。我不知道身份验证出了什么问题,谢谢您提前的答复!

1 个答案:

答案 0 :(得分:0)

您可以使用express-session实现相同的目的。

  1. 安装express-session:npm i express-session --save
  2. 在您的节点应用程序中要求它:var session = require('express-session');
  3. 配置:app.use(session({ secret: "YourSecretKeyGoesHere", saveUninitialized: true, resave: true }));

然后检查您的会话。