mongodb 为什么每次服务器请求都要将会话保存到我的数据库中?

6yt4nkrj  于 2023-08-04  发布在  Go
关注(0)|答案(1)|浏览(86)

我有一个express应用程序,它使用express-session和connect-mongodb-store作为用户会话。当用户登录时,setp正常工作,他们的护照被保存到数据库中,并且他们保持登录状态。但是,我的数据库似乎被许多没有护照的会话所填充。在测试中,我注意到几乎每个服务器请求都会创建一个会话。
下面是服务器代码:

const express = require("express");
const bodyParser = require("body-parser");
const passport = require("passport");
const flash = require("express-flash");
var session = require('express-session');
const mongoose = require('mongoose');
const uri = process.env.MONGODB_URI;
const MongoDBStore = require('connect-mongodb-session')(session);
const initializePassport = require(__dirname+"/passport-config.js");
const methodOverride = require("method-override");
const PORT=process.env.PORT || 3000;

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
initializePassport(passport);

app.use(
  session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    cookie: {
    maxAge: 1000 * 60 * 60 * 24 * 7 // 1 week
  },
    saveUninitialized: false,
    store: new MongoDBStore({
      uri: process.env.MONGODB_URI,
      collection: "sessions",
      mongooseConnection: mongoose.connection,
    }),
  })
);

app.use(flash());

app.use(passport.initialize());
app.use(passport.session());
app.use(methodOverride("_method"));

app.use((req,res,next)=>{
  user=req.user;
  next();
})
//routes
...
///
mongoose.connection.once("open", () => {
  app.listen(PORT, () => {
    console.log(`Server started on port ${PORT}`);
  });
});

mongoose.connection.on("error", (err) => {
  console.error("MongoDB connection error:", err);
});

字符串
以下是用户登录时保存的数据:

{"_id":"RaJ_m6eXHCD4favlq6E15tljWv-OiCjc","expires":{"$date":{"$numberLong":"1691015547496"}},"session":{"cookie":{"originalMaxAge":null,"expires":null,"secure":null,"httpOnly":true,"domain":null,"path":"/","sameSite":null},"flash":{},"passport":{"user":"646ef8adfa61e6eac440db91"}}}


以及为请求创建的许多其他会话:

{"_id":"QvqtxeS1UCQPy9v-xsCThbqM8XPC5o4q","expires":{"$date":{"$numberLong":"1691015549321"}},"session":{"cookie":{"originalMaxAge":null,"expires":null,"secure":null,"httpOnly":true,"domain":null,"path":"/","sameSite":null},"flash":{}}}


任何见解将不胜感激!谢谢你,谢谢
我试过移动app.use(express.static(“public”)); initializePassport(护照);周围,但似乎没有帮助。我也尝试过在添加新会话之前检查会话是否存在:

app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false,
  store: new MongoDBStore({
    uri: process.env.MONGODB_URI,
    collection: "sessions",
    mongooseConnection: mongoose.connection,
  }),
  // Check if a session already exists before creating a new one
  // This avoids storing a session on every page load
  genid: function (req) {
    return req.sessionID || null;
  }
}));


但是,用户的护照信息没有保存,因此无法登录
edit:这里还有passport-config

const LocalStrategy = require("passport-local").Strategy;
    const bcrypt = require("bcrypt");
    const db=require(__dirname+"/db.js");
    
    function initialize(passport){
        const authenticateUser = async (username,password,done) =>{
            const user = await db.findUserByUsername(username.toLowerCase());
            if(user==null){
                return done(null, false, {message: "No user with that username"})
            }
    
            try{
                if (await bcrypt.compare(password, user.password)){
                    return done(null, user)
                } else{
                    return done(null, false, {message: "password incorrect"})
                }
            } catch (e){
                return done(e)
            }
        }
    
        passport.use(new LocalStrategy({usernameField: "username"},authenticateUser));
        passport.serializeUser((user, done) =>  done(null, user.id))
        passport.deserializeUser(async (id, done) => { 
            const user=await db.findUserByID(id)
            done(null, user);
         })
    }
    
    module.exports = initialize;

tp5buhyn

tp5buhyn1#

尝试此代码它将在一周后自动过期会话.这里有一些参考代码

const MongoDBStore = require('connect-mongodb-session')(session);

const store = new MongoDBStore({
  uri: process.env.MONGODB_URI,
  collection: 'sessions',
  mongooseConnection: mongoose.connection,
  expires: 7 * 24 * 60 * 60 * 1000,
});
    store.on('error', function (error) {
  console.error('MongoDB Session Store Error:', error);
});

app.use(
  session({
    secret: 'your-secret-key',
    resave: false,
    saveUninitialized: false,
    store: store,
    cookie: {
      maxAge: 7 * 24 * 60 * 60 * 1000, // The same value as the TTL (e.g., 7 days)
    },
  })
);

字符串

相关问题