Hello I am fairly new to connect-mongodb-session library so I would love to know how I can access the collection of user sessions so that I can have a code logic to check if user session has expired so that I can remove it from collection.
I know with connect-mongo:
I can set it up like this below to check each hour for expired sessions and it automatically removes the expired sessions
const sessionStore = new MongoStore({
db: 'myappsession',
clear_interval: 3600
});
But now with connect-mongodb-session there's no prop 'clear_interval'
This is how my connect-mongodb-session store is made:
const mongoStore = MongoStore(expressSession);
const store = new mongoStore({
collection: "userSessions",
uri: process.env.mongoURI,
expires: 10 * 1000 * 24 * 60 * 60,
});
So when things are like this how can I go about this
var store=mongoDbStore({
uri:connectionString,
collection:"mySessions"
})
app.use(
session({
secret:key,
resave: true,
saveUninitialized:false,
cookie:{
maxAge:3600000
},
store:store
})
)
You can give a maxAge like above. This session will be terminated.
Related
In my NodeJs / Express app, I'm using the standard session package and Passport to handle sessions and login. My problem is that the app kicks the user out after what feels like 10 minutes of inactiviy, and forces them to log-in again. My assumption is that it must be something to do with the session configuration, which with my limited understanding, I think is configured to allow 2 hours:
const session = require("express-session");
const PostgreSqlStore = require("connect-pg-simple")(session);
const sessionAge = 2 * 60 * 60 * 1000; // hour, min, sec, millisecond
var sessionConfig = {
name: "mysite",
secret: "verysecret",
resave: true,
saveUninitialized: false,
proxy: trustedTypes,
cookie: {
key: "cookieKey",
secure: true,
sameSite: false,
httpOnly: true,
maxAge: sessionAge,
},
store: new PostgreSqlStore({
pgPromise: db,
ttl: 2 * 60 * 60, //Hours, minute, seconds
}),
};
app.use(session(sessionConfig));
Is there anything I'm doing wrong, or is there something else I should be looking at to find the cause of this behavior?
store: new PostgreSqlStore({
pgPromise: db,
ttl: 2 * 60 * 60, //Hours, minute, seconds
})
I think your PostgreSQL store ttl property should be equivalent to maxAge property of session config
I've discovered that apparently although by default the session does get extended on the server, it won't send an updated cookie to the browser if nothing has changed in it. The missing property is the 'rolling' attribute.
var sessionConfig = {
rolling: true,
I am using mongoose for managing relationships between data and I am trying to use connect-mongo to store specific sessions in the database.
It looks like that we need to connect twice to the db, one with mongoose and another one with connect-mongo.
I am using the following code to initialise a connection for mongoose
await mongoose.connect(this._connectionUrl, this._connectionOptions);
Initialising a new store every time (not sure if I am correct regarding code initialisation).
app.use(session({
// secret: config.sessionSecretKey,
secret: "secretkey",
resave: true,
saveUninitialized: true,
cookie: { maxAge: 19 * 60000 }, // store for 19 minutes
store: MongoStore.create({
mongoUrl: this._connectionUrl,
mongoOptions: this._connectionOptions // See below for details
})
}))
Is there any way that I can pass the connection from mongoose to mongo-connect Store?
i'm lookin for a solution too and just read this on the "migration guide" of connect-mongo
For the options, you should make the following changes:
Change url to mongoUrl Change collection to collectionName if you are
using it Keep clientPromise if you are using it mongooseConnection has
been removed. Please update your application code to use either
mongoUrl, client or clientPromise To reuse an existing mongoose
connection retreive the mongoDb driver from you mongoose connection
using Connection.prototype.getClient() and pass it to the store in the
client-option. Remove fallbackMemory option and if you are using it,
and there's this example https://github.com/jdesboeufs/connect-mongo/blob/master/example/mongoose.js
I've just been digging through the docs and through a few other SO responses. I've found this works really well with the new version of connect-mongo.
const session = require('express-session');
const MongoStore = require('connect-mongo');
app.use(
session({
secret: "secretkey",
resave: true,
saveUninitialized: true,
cookie: { maxAge: 19 * 60000 }, // store for 19 minutes
store: MongoStore.create({
client: mongoose.connection.getClient()
})
})
);
It is recommended by the devs for connect-mongo to utilise the connection object for mongoose to retrieve the client to ride the same connection so you don't have to setup two separate connections. This seems like a really clean way to do it but comment if you spot anything off!
This was pulled from the bottom of the connect-mongo migration guide here
When I restart my server, my session ends and I am logged out. This does not happen on a regular page refresh. I am using connect-mongo to remedy this:
var session = require('express-session');
const MongoStore = require('connect-mongo')(session);
Here is the code I am using to store my session, reusing an existing Mongo connection called thisDb:
app.use(session({
secret: secretHash,
saveUninitialized: true,
resave: true,
secure: false,
store: new MongoStore({ db: thisDb })
}));
During a successful log in:
var day = 60000*60*24;
req.session.expires = new Date(Date.now() + (30*day));
req.session.cookie.maxAge = (30*day);
In my Mongo shell, I can verify that a new session is created when I log in:
db.sessions.find()
{"cookie":{"originalMaxAge":2592000000,"expires":"2017-11-17T20:36:12.777Z","httpOnly":true,"path":"/"},"user":{"newNotifications":false,"username":"max","admin":"true","moderator":"true"},"expires":"2017-11-17T20:36:10.556Z"}
Well, almost 3 years later i was having this issue. Don't know if OP was using Passport but i resolved this issue by moving this functions from inside the passport.use function to outside:
passport.serializeUser(function(user, done){
done(null,user.id);
});
passport.deserializeUser((id,done) => {
User.findById(id, (err,user) => {
done(null,user);
});
});
The simple example on https://github.com/voxpelli/node-connect-pg-simple shows:
var session = require('express-session');
app.use(session({
store: new (require('connect-pg-simple')(session))(),
secret: process.env.FOO_COOKIE_SECRET,
resave: false,
cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 } // 30 days
}));
But when I try it, node complains:
throw new Error('No database connecting details provided to
connect-pg-simple');
How do I specify the connection string?
// I was stuck with the same proble and solved it
// 1-) Connection details
const conObject = {
user: 'mehmood',
password: 'mehmood',
host: 'localhost',// or whatever it may be
port: 5432,
database: 'test_db'
};
// 2-) Create an instance of connect-pg-simple and pass it session
const pgSession = require('connect-pg-simple')(session);
// 3-) Create a config option for store
const pgStoreConfig = {
pgPromise: require('pg-promise')({ promiseLib: require('bluebird') })({
conObject }), // user either this
//conString: 'postgres://mehmood:mehmood#localhost:5432/test_db', // or this
// conObject: conObject,// or this,
// pool: new (require('pg').Pool({ /* pool options here*/}))// or this
}
// 4-) use the store configuration to pgSession instance
app.use(session({
store: new pgSession(pgStoreConfig),
secret: 'jW8aor76jpPX', // session secret
resave: true,
saveUninitialized: true,
cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 } // 30 days
}));
// Share improve this answer
For me it worked like
conString:'postgres://postgres:password123#localhost:5432/edu';
So the format must be
conString:'postgres://<user>:<database_password>#<hostname>:<port>/<database_name';
For deploying you get a username. If you run on local machine then PostgreSQL
I have an Express 4 app setup to have sessions.
// Sessions
app.use(cookieParser());
app.use(session({ secret: "some-secret" }));
// Signup
app.post("/signup", function (req, res) {
create_user(req.body.user, function (err, user_id) {
req.session.user_id = user_id;
res.redirect("/admin");
});
});
When I submit the form, it saves the user_id to the req.session. However, when I restart the server, the session is gone.
Why isn't it persisting? Am I missing some configuration?
The default session store for express-session is MemoryStore, which as the name suggests, stores sessions in memory only. If you need persistence, there are many session stores available for Express. Some examples:
Cookie store
Redis store
MongoDB store
CouchDB store
Riak store
memcached store
leveldb store
MySQL store
PostgreSQL store
Firebase store
For a updated and more complete list visit Compatible Session Stores.
#mscdex answer is great but in case you are looking for code samples. Here is one with connect-mongo which should work fine if you mongodb and mongoose.
Install the package:
npm i connect-mongo
require the package:
const session = require('express-session'); // You must have express-sessions installed
const MongoStore = require('connect-mongo')(session)
Now configure the session:
app.use(
session({
secret: "mysecrets",
resave: false,
saveUninitialized: false,
store: new MongoStore({
mongooseConnection: mongoose.connection,
ttl: 14 * 24 * 60 * 60
}),
})
);
Again this assumes you are using mongoose and have the connection configured.
If you did everything right, it should work just fine.