everybody. I have a problem about session manage.
This is my "express-session" configuration (app.js):
app.use(session({
secret: "I love pizza...",
resave: true,
saveUninitialized: true
}));
When user logged, I storage some 'attributes' in req.session like this (controller.js):
exports.login = function (request, response) {
request.session.username = 'admin';
response.render('pages/home', {
title: "home",
username: request.session.username
});
}
It show me 'home' page with 'menu' and other links. One link has a 'href' that redirect to 'dashboard' page:
<a class="nav-link active d-flex align-items-center nav-link-2"
href="/dashboard">
<span>Dashboard</span>
</a>
And it is routed in routes.js:
function sessionChecker (req, res, next) {
if (req.session && req.session.username) {
next();
} else {
res.redirect('/login');
}
};
app.get('/dashboard', sessionChecker, home.evaluacion_dash);
Well, the issue is sessionChecker method, the variable req.session.username doesn't exist.
On the other hand, if I replace response.render by response.send method, like this:
response.send('login success!!!');
It show me the page with a text: 'login success!!!' and if I write (manually) in the address bar: 'http://localhost:3000/dashboard', the variable req.session.username exists in sessionChecker method....
Any suggestions about the configuration in express-session or another alternative to be able to persist the 'username'?
Additional info: node version: 8.9.3, express version: 4.13.1, express-session version: 1.15.6
Regards!
My First opinion to use passportjs that handles sessionChecker for you.
Maybe you have to change resave and saveUninitialized here
app.use(session({
key: 'session_cookie_name',
secret: 'session_cookie_secret',
resave: false,
saveUninitialized: false
}));