I'm using Express Session along with Mongo Store. My session is configured so that it stores it's sessions in a Mongo Database. When I visit the app, a new session is being created. I want it so that a session is created ONLY when a user signs up and a session is resumed when the user logs in. I also want to remove a session after 24 days.
This is my configuration code: (I put an actually mongo url when I was testing)
app.use(session({
secret: "secretakey",
resave: false,
saveUninitialized: true,
store: MongoStore.create({ mongoUrl: "mongourlwenthereintesting", autoRemove: "native", touchAfter: 24 * 24 * 3600 }),
cookie: { secure: false, maxAge: 1000 * 60 * 60 * 24 * 20 },
rolling: true
}));
Related
i am using connect-mongo for storing sessions in the database and locals for sending flash to the frontend, but this is causing an error with connect-flash: sometimes when i flash a message in the backend the popup won't show up.
// sessions
const session = require('express-session');
var MongoDBStore = require('connect-mongo');
var store = MongoDBStore.create({
mongoUrl: MONGO_URI,
ttl: 7 * 24 * 60 * 60,
touchAfter: 24 * 60 * 60,
});
store.on('error', function(error) {
console.log(error);
});
const sessionConfig = {
store: store,
name: "sid",
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true,
expires: Date.now() + 1000 * 60 * 60 * 24 * 7,
maxAge: 1000 * 60 * 60 * 24 * 7,
},
};
app.use(session(sessionConfig))
when i remove store: store; the code works fine
i have tried using express-mysql-session
const MySQLStore = require('express-mysql-session')(session);
app.use(cookieParser())
const sessionStore = new MySQLStore(db);
const sessionConfig = {
name: 'session',
// store: sessionStore,
secret: '25658595',
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
expires: Date.now() + 1000 * 60 * 60 * 24 * 7,
maxAge: 1000 * 60 * 60 * 24 * 7
},
};
const mysql = require('mysql');
require('dotenv').config();
const connection = mysql.createConnection({
socketPath:'',
host: '',
user: '',
password: '',
database: '',
multipleStatements: true
})
connection.connect((err) => {
if (err) throw err;
console.log('Database Connected')
})
module.exports = connection;
When i able session store property the server respond with an error 502 and when i disable session store property all things work fine
Warning: connect.session() MemoryStore is not
designed for a production environment, as it will leak
memory, and will not scale past a single process.
on port 8081
Because of this message i have used express-mysql-session
This is my first time posting a question up here. I hope you guys can help me out with this. I am fairly new to node.js, express, so sorry in advance for my inexperience.
I am currently having a problem with my authentication session in my node.js, express app. I use Passport.js to handle my authentication, I store the login session with connect-pg-simple (a PostgreSQL session store). After clicking the login button, the session was stored inside my PostgreSQL database, but somehow express couldn't find it. In fact, it stores the session twice in the database, but only one of them got the passport cookie in it.
This issue was not present when the server was still on localhost. It appears when I host my server on Heroku.
Also, whenever I push to heroku repo, it shows this warning:
"connect.session() MemoryStore is not designed for a production environment, as it will leak memory, and will not scale past a single process."
My guess is I didn't connect express session to the PostgreSQL express store properly. Below is my code:
This is how I set up the PostgreSQL database:
const Pool = require("pg").Pool;
const pool = new Pool({
user: process.env.PGUSER,
password: process.env.PGPASSWORD,
host: process.env.PGHOST,
port: process.env.PGPORT,
database: process.env.PGDATABASE
});
module.exports = pool
This is how I set up the session:
const poolSession = new (require('connect-pg-simple')(session))({
pool : pool
})
app.set('trust proxy', 1);
app.use(session({
store: poolSession,
secret: process.env.SESSION_SECRET,
saveUninitialized: true,
resave: false,
cookie: {
secure: true,
maxAge: 30 * 24 * 60 * 60 * 1000
} // 30 days
}));
app.use(passport.initialize());
app.use(passport.session());
This is the image of 2 sessions were store in the database when clicking the login button
https://i.stack.imgur.com/lzAby.png
This is my login route (when click the login button):
router
.route("/signin")
.post((req, res, next) => {
console.log("Signing in...")
passport.authenticate('local', function(err, user, info) {
//code....
req.logIn(user, function(err) {[enter image description here][1]
console.log(user);
if (err) {
console.log(err);
res.send(apiResponse(500, err.message, false, null))
return next(err);
}
console.log(req.sessionID); //The id of the 1st session store in db
console.log(req.isAuthenticated()) //True
res.redirect('/auth');
});
})(req, res, next);
})
This is the route that is redirected to when login successfully:
router.get("/", (req, res) => {
console.log("/ ", req.isAuthenticated()); //False
console.log("/ ", req.sessionID); //The Id of the 2nd session store in db
if(req.isAuthenticated()){
//Notify user login success
}
});
I have been stuck here for a few days now. Please tell me if you need more code!
I have the following code to set up a session store with connect-mong
var express = require('express');
var MongoStore = require('connect-mongo')(express);
var app = express();
app.use(express.cookieParser());
app.use(express.session({
secret: '1234567890QWERTY',
maxAge: new Date(Date.now() + 3600000),
store: new MongoStore({
db: 'mydb',
host: '127.0.0.1'
}),
cookie: { maxAge: 24 * 60 * 60 * 1000 }
}));
In the requests and responses from the server I can see the sessionIDs, but the database is not created or if I create it the session collection does not gets filled. I do not receive any errors on the console.
I cannot find what am I missing ( using express 3).
It happens because nobody connected yet to your express server. So there's no session to store.
Add
app.listen(3000, function() {
console.log('now listening on http://localhost:3000/');
});
At the end and connect to the server in your browser. Immediately you will get sessions collections in your Mongo db.
I had multiple use of the session and cookieParser. This caused the problem.
i'm using
node 0.4.11
express 2.4.6
mongodb 1.8.3
mongoose 2.1.2
connect-mongodb 1.0.0
and trying to implement replica sets with authentication.
i want to store different kind of application-data in the DB
i want to store express' session-data in the DB
a "normal" connection with mongoose is working:
mongo.connectSet('mongodb://user:secret#host:27017/test,
mongodb://host:27018,
mongodb://host:27019,
mongodb://host:27020', function (err) {
if (err) {
console.log("could not connect to DB: " + err);
}
});
but how can get the session management to work?!
app.use(express.session({
cookie: {maxAge: 60000 * 20}, // 20 minutes
secret: 'foo',
store: new MongoStore({
host: 'host',
port: [27017, 27018, 27019, 27020],
dbname: 'test',
rs_name: 'rstest',
username: 'user',
password: 'secret'
})
}));
this is not working :(
is this actually possible? or should i use a different mongodb for storing the session data?
Are you sure you are using connect-mongodb and not connect-mongo?
I don't see where those parameters can be used with connect-mongodb.
Don't pass in the connection settings. connect-mongodb can take a direct db variable instead, which is an instance of mongodb.Db.
That means you can use the same connection that mongoose uses, instead of having connect-mongodb create a new connection just for sessions.
For mongoose, the mongodb.Db instance can be found at mongoose.connection.db.
So using your code as an example (assuming mongo is your mongoose object):
app.use(express.session({
cookie: {maxAge: 60000 * 20}, // 20 minutes
secret: 'foo',
store: new MongoStore({db: mongo.connection.db})
}));