具有connect-session-sequelize的持久会话

时间:2017-08-10 16:32:40

标签: node.js postgresql session express persistent

我正在建立一个带登录系统的网站,我希望用户即使在浏览器关闭后也能保持登录状态。仅在用户注销时销毁会话。我在网上搜索了解决方案,并提出了使用connect-session-sequelize的建议。我阅读了文档并尽最大努力使代码工作,但我在这方面缺乏经验。

问题:

我的代码没有告诉我在服务器重启后保持用户登录的结果。我的代码是:

var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
var session = require('express-session');
var SequelizeStore = require('connect-session-sequelize')(session.Store);

var pug = require('pug');
var bodyParser = require('body-parser');
var bcrypt = require('bcrypt');

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(express.static('public'));
app.use(cookieParser());

app.set('views', './views');
app.set('view engine', 'pug');

var Sequelize = require('sequelize');
var db = new Sequelize('postgres://'+ process.env.POSTGRES_USER + ':' + 
process.env.POSTGRES_PASSWORD + '@localhost/terranova', {
    host: 'localhost',
    dialect: 'postgres',
    storage: './session.postgres', 
    define: {
      timestamps: true
    }
});

var sessionStore = new SequelizeStore({
    db: db,
    checkExpirationInterval: 15 * 60 * 1000,
    expiration: 24 * 60 * 60 * 60 * 1000 
});

app.use(session({
  secret: 'salajhgdusdajss',
  store: sessionStore,
  resave: false,
  saveUninitialized: false,
  proxy: true
}));

sessionStore.sync()

var Session = db.define('Session', {
    sid: {
      type: Sequelize.STRING,
      primaryKey: true
    },
    userId: Sequelize.STRING,
    expires: Sequelize.DATE,
    data: Sequelize.STRING(50000)
});

var User = db.define('user', {
  username: Sequelize.STRING,
  password: Sequelize.STRING,
});

function extendDefaultFields(defaults, session) {
  return {
    data: defaults.data,
    expires: defaults.expires,
    userId: session.userId
  };
}

var store = new SequelizeStore({ 
   db: db,
   table: 'Session',
   extendDefaultFields: extendDefaultFields
});

子问题

  1. 文档指示添加'var store = new SessionStore'而不是'var store = new SequelizeStore',但它给出了一个错误:'SessionStore未定义'。不确定我做错了什么?

  2. 我可以在'用户'表中看到,但出于某种原因,我无法查看'Sessions'表,其中'select * from Sessions;'我得到'关系'会话“不存在”的回应。为什么会这样? enter image description here

  3. 到期时间:24 * 60 * 60 * 1000 - >默认有效期为24小时。这是否表明会议的时间?如果是,最大可能时间是多少(如果不可能无限制)?

  4. 有人可以解释一下我需要做什么/添加/删除我的代码才能实现我的目标?

    有关详细信息,请参阅登录页面...

    app.get('/login', function(req,res) {
        res.render('login')
    })
    
    app.post('/login', function(req,res) {
        var username = req.body.username
        var password = req.body.password
    
        User.findOne({
            where: {
                username: username
            }
        }).then(function(user) {
            if(username.length === 0 || password.length === 0) {
                 res.render('login', {
                    message: "Username or password missing"
                });
                return;
            };
            if(user == null) {
                res.render('login', {
                    message: "User not in the system, please register"
                }); 
                return;
            } else {
                var hash = user.password
                bcrypt.compare(password, hash, function(err, result) {
                    if (err) {
                        res.render('login', {
                            message: 'Invalid email or password, please try again or register'
                        })
                    };
                    if(result === true) {
                        req.session.user = user;
                        res.redirect('/home');
                    }
                    else {
                        res.render('login', {
                            message: "Something went wrong, please try again"
                         });
                    };
                });
            };
        });
    })
    

    ......这是主页。

    app.get('/home', function(req,res) {
        var user = req.session.user
    
        if (user === undefined) {
            res.render('login', {
                message: 'Please log in to have the access'
            });
        } else {
            res.render('home', {
                user: user
            });
        }
    })
    

    非常感谢帮助我!

0 个答案:

没有答案