简体   繁体   English

在 node.js 中重定向后 Express 会话不会持续存在

[英]Express sessions not persisting after redirect in node.js

Using node.js and pgAdmin.使用 node.js 和 pgAdmin。 I have set up all the necessary code for a server, sessions, cookies, and all that.我已经为服务器、会话、cookies 等设置了所有必要的代码。 The error I'm getting is "TypeError: Cannot read property 'username' of undefined".我得到的错误是“TypeError:无法读取未定义的属性'用户名'”。 The session will not persist after it redirects from one page to another. session 从一页重定向到另一页后将不会持续存在。 Specifically from the loginregister page to the orderform.特别是从登录注册页面到订单。 How do I get the session to stay after being redirected?重定向后如何让 session 保持不变? Any help would be greatly appreciated, thanks!任何帮助将不胜感激,谢谢!

const LocalStrategy = require("passport-local").Strategy;
const { pool } = require('./dbConfig');
const bcrypt = require('bcryptjs');

function initialize (passport) { 
           
    const authenticateUser = (username, password, done) => {

        pool.query(

            `SELECT * FROM credentials WHERE username = $1`, 

            [username], (err, results) => {

                if(err) {
                    throw err;
                }

                if(results.rows.length === 1) {
                    const user = results.rows[0];

                    bcrypt.compare(password, user.password, (err, isMatch) => {
                        if(err){
                            throw err
                        }
                        if(isMatch){
                            
                            return done(null, user);
                        }
                        else {
                            return done(null, false, {message: "Incorrect password"});
                        }
                    })
                }
                else {
                    return done(null, false, {message: "Account does not exist"});
                }
            }
        );
    }

    passport.use('user-local', new LocalStrategy({
        usernameField: "username",
        passwordField: "password"
    }, authenticateUser));

    passport.serializeUser(function (user, done) 
    { 
        done(null, user.user_id);
    });

    passport.deserializeUser(function (id, done) { console.log("---------------------------------------------");
        pool.query(
            `SELECT * FROM credentials WHERE user_id = $1`,
            [id],
            (err, results) => {
                if(err) {
                    throw err;
                }
                return done(null, results.rows[0]);
            }
        )
    });

    const authenticateEmp = (username, password, done)=>{
        pool.query(
            `SELECT * FROM employee WHERE username = $1`, 
            [username], (err, results) => {
                if(err) {
                    throw err;
                }

                if(results.rows.length == 1) {
                    const user = results.rows[0];

                    bcrypt.compare(password, user.password, (err, isMatch) => {
                        if(err){
                            throw err
                        }
                        if(isMatch){
                            return done(null, user);
                        }
                        else {
                            return done(null, false, {message: "Incorrect password"});
                        }
                    });
                }
                else {
                    return done(null, false, {message: "Account does not exist"});
                }
            }
        );
    }

    passport.use('emp-local', new LocalStrategy({//Create admin controler 
        usernameField: "username",
        passwordField: "password"
    }, authenticateEmp));

    passport.serializeUser((user, done) => done(null, user.user_id));
    passport.deserializeUser((id, done) => {
        pool.query(
            `SELECT * FROM employee WHERE emp_id = $1`,
            [id],
            (err, results) => {
                if(err) {
                    throw err;
                }
                return done(null, results.rows[0]);
            }
        );
    });
}

module.exports = initialize;
userRouter.get("/loginregister", (req, res) => {
  res.render("../views/loginRegister");
});

userRouter.get("/orderform", (req, res) => {
  console.log(req.user);
  res.send(`Hello ${req.user.username}. Your session ID is ${req.sessionID} 
  and your session expires in ${req.session.cookie.maxAge} 
  milliseconds.<br><br>
  <a href="/logout">Log Out</a><br><br>
  <a href="/secret">Members Only</a>`);
    //res.render("../views/orderForm");
});
function loginController (req, res, next) {
    passport.authenticate('user-local', function(err, user, info) {
      if (err) { return next(err); }
      if (!user) { return res.redirect('/loginregister'); } // Can attach flash message here and personalize req.body.email 
      req.logIn(user, function(err) {
        if (err) { return next(err); }
        console.log(req.sessionID);
        return res.redirect('/user/orderform');
      });
    })(req, res, next);
};

const { name } = require("ejs");
const express = require("express");
const app = express();
const path = require('path');
const parseurl = require('parseurl')
const session = require("express-session");
const flash = require("express-flash");
const uid = require('uid-safe');
const assert = require('assert');
const pgStore = require('connect-pg-simple')(session);
const router = require('../views/routes');
const passport = require('passport');
const { pool } = require('./dbConfig');
const passportConfig = require("./passportConfig");
const PORT = process.env.PORT || 4000;

app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: false }));

uid(18, function (err, val) {
  if (err) return done(err)
  assert.strictEqual(Buffer.byteLength(val), 24);
})

app.use(session({
  genid: function(req) {
    return uid(18) // use UUIDs for session IDs
  },

  secret: process.env.SECRET_KEY,
  resave: 'false',
  saveUninitialized: 'false',
  cookie: { 
    secure: false,
    maxAge: 24 * 60 * 60 * 1000 // One day
  }, 

  store: new pgStore({
    pool : pool,                // Connection pool
    tableName : process.env.TABLE_NAME   
    // Insert connect-pg-simple options here
  })

}));

if (app.get("env") === "production") {
    // Serve secure cookies, requires HTTPS
    session.Cookie.secure = true;
  }

app.use(flash());

passportConfig(passport);
app.use(passport.initialize());
app.use(passport.session());

app.use(express.json());

app.use ('/', router);

app.use(express.static(path.resolve(__dirname, './css')));

app.listen(PORT, () => {

    console.log(`Server running on port ${PORT}`);
});

To debug why you're not getting a session cookie, replace your existing session middleware with just this:要调试为什么您没有获得 session cookie,请将现有的 session 中间件替换为:

app.use(session({ 
    secret: 'keyboard cat', 
}));

Verify that your session cookie works with that.验证您的 session cookie 是否适用。 Then, if so, start adding your session options back one at a time until you find the one that causes things to stop working.然后,如果是这样,开始一次添加一个 session 选项,直到找到导致事情停止工作的选项。

A few other notes.其他一些注意事项。

Your uid implementation for express-session is not implemented properly.您对 express-session 的 uid 实现未正确实现。

To start with, express-session has its own uid generator built in. You don't need to provide one yourself unless you have some specific unique requirement that the built-in generator does not satisify.首先,express-session 内置了自己的 uid 生成器。您不需要自己提供一个,除非您有一些内置生成器无法满足的特定独特要求。

According to the doc for uid-safe, a synchronous UID is generated with:根据 uid-safe 的 文档,生成同步 UID:

 uid.sync(18)

not, what you are using which is just uid(18) .不,您正在使用的只是uid(18) That just returns a promise object which will not work for a unique id.这只会返回一个 promise object ,它不适用于唯一 ID。

So, this:所以这:

genid: function(req) {
  return uid(18);
},

should be this:应该是这样的:

genid: function(req) {
  return uid.sync(18);
},

Or, just leave the uid generation for express-session to do it on its own.或者,让快速会话的 uid 生成自行完成。

Oh, here's a fun fact, the default implementation in express-session already uses uid-safe .哦,这是一个有趣的事实, express-session 中的默认实现已经使用uid-safe

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM