错误:无法将用户序列化到与节点js、passport和mysql数据库的会话中

46qrfjad  于 2021-06-21  发布在  Mysql
关注(0)|答案(0)|浏览(175)

我将mysql数据库用于我的node js应用程序。使用passport进行身份验证。这是我的passport.js文件。

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

var mysql = require('mysql');

var connection = mysql.createConnection({
    host     : "localhost",
    user     : "root",
    password : "",
    database: "cafe"
});
connection.connect(function(err){
    if(err) throw err;

    else console.log("Passport Server Connected");
});

passport.serializeUser(function(user, done) {
    console.log("In Serialize !"+ user.ID);
    done(null, user.id);
});

// used to deserialize the user
passport.deserializeUser(function(id, done) {
    connection.query("select * from user where id = "+id,function(err,rows){
        console.log("Inside Deserialize ---> "+rows[0]);
        done(err, rows[0]);
    });
});

// https://gist.github.com/manjeshpv/84446e6aa5b3689e8b84 
// Passport with mysql database

passport.use('local-signup', 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) {

      connection.query("select * from user where email = '"+email+"'",function(err,rows){
        console.log(rows);
        console.log("above row object");
        if (err)
            return done(err);
            if (rows.length > 0) {
            // return done(null, false, req.flash('signupMessage', 'That email is already taken.')); // Not Working
            return done(null, false, {message : 'Email Id Already Taken !'}); //Default Json Unauthorised
        } else {
            // if there is no user with that email
            // create the user

            var newUserMysql = new Object();
            newUserMysql.email    = email;
            newUserMysql.password = password; // use the generateHash function in our user model
            console.log(newUserMysql);
            var insertQuery = "INSERT INTO user ( email,password ) VALUES ('"+ email +"','"+ password +"')";
            console.log(insertQuery);
            connection.query(insertQuery,function(err,rows){
                newUserMysql.id = rows.insertId;
                if(err) throw err;
                // console.log("Error is "+ err);
                // console.log(insertQuery);
                return done(null, newUserMysql);
            });
        }   
    });
    // 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.query("SELECT * FROM `user` 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
            return done(null, false, {message: 'No User Found! '});
        } 

        // if the user is found but the password is wrong
        if (!( rows[0].password == password )){
            // return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
            return done(null, false, {message: 'Oops! Wrong Password! '});
        }
        // all is well, return successful user
        console.log(" Inside callback of local-login -> "+rows[0]);
        return done(null, rows[0]);         
    });
}));

// module.exports;

根据我的应用程序,每当我在注册页中创建一个新用户时,它都会成功地创建该用户,并且通过调用serialize和deserialize函数来创建会话。
但是当我尝试登录用户时,它产生了这个错误。只有serialize在工作,并且在登录过程中未调用反序列化函数。
但是如果我禁用与session:false,它正在让我登录,但是没有我不想要的会话。
这是我的路线文件。

var express = require('express');
var router = express.Router();
async = require('async');
var csrf = require('csurf');
var passport = require('passport');
var csrfProtection = csrf();
router.use(csrfProtection);

// Profile Routes

router.get('/profile',function(req,res,next){
    res.render('user/profile');
});

// SIGN UP Routes 

router.get('/signup',function(req,res,next){
    var messages = req.flash('error');
    // console.log("In Get Route "+ messages +" is the Error"); //req.flash not working.
    res.render('user/signup', {csrfToken:req.csrfToken(), messages: messages , hasError: messages==undefined ?false :messages.length>0});
});

router.post('/signup',passport.authenticate('local-signup',{
    successRedirect:'/user/profile',
    faliureRedirect : '/user/signup',
    // faliureMessage:'Not Valid',
    faliureFlash:true,
    // session:false
}));

//Sign In
router.get('/signin',function(req,res,next){
    var messages = req.flash('error');
    // console.log("In Get Route "+ messages +" is the Error"); //req.flash not working.
    res.render('user/signin', {csrfToken:req.csrfToken(), messages: messages , hasError: messages==undefined ?false :messages.length>0});
});

router.post('/signin',passport.authenticate('local-login',{
    successRedirect:'/user/profile',
    faliureRedirect : '/user/signin',
    faliureFlash:true,
    // session:false,
}));

//Log Out   
router.get('/logout',function(req,res,next){
    req.logOut();
    res.redirect('/');
});

module.exports = router;

如果我可以问的话,我的闪光灯也坏了。任何帮助都将不胜感激。
请注意,我的注册工作正常,所以基本上会话正在创建中,序列化和反序列化函数也正常工作。问题仅在登录会话中出现

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题