Reputation: 373
I'm trying to use a session ID from my mongo database as the sessionID within express-session and have these details stored within a connect-redis session store.
I keep getting 'TypeError: cookie required'
This appears to be a bug, but could somebody check my logic here please:
I've stripped the code down to it's bare bones and removed anything that's not required to create the issue.
'use strict';
var express = require('express'),
session = require('express-session'),
redisStore = require('connect-redis')(session),
bodyParser = require('body-parser'),
app = express();
app.use(session({
name: 'test',
genid: function(req) {
if (typeof req.sessionID != 'undefined') return req.sessionID;
},
cookie: {
httpOnly: false,
path: '/',
maxAge: null
},
resave: false,
saveUninitialized: false,
secret: 'finbarboobar',
store: new redisStore({
host: 'localhost',
port: 6379,
prefix: 'kTest:'
})
}));
app.use(bodyParser.urlencoded({ extended: false }));
//router
app.route(['/'])
.get(function(req, res) {
if (req.session.email) return res.redirect('/admin');
res.send('<h1>Login</h1><form action="/login" method="POST" accept-charset="UTF-8" ><input placeholder="Enter Email" name="email" type="email" autofocus="autofocus"><input type="submit" value="sign in"></form>');
});
app.route(['/login'])
.post(function(req, res) {
req.sessionID = 1;
req.session.regenerate(function(error) {
if (error) {
console.log(error);
} else {
req.session.email = req.body.email;
res.redirect('/admin');
}
});
});
app.get('/admin', function(req, res) {
if (req.session.email) {
res.send('<h1>Hello ' + req.session.email + '</h1><a href="/logout">logout</a>');
} else {
res.redirect('/');
}
});
app.get('/logout', function(req, res) {
req.session.destroy(function(error) {
if (error) {
console.log(error);
} else {
res.redirect('/');
}
})
});
app.listen(3001);
Thanks for looking at this.
Upvotes: 2
Views: 1126
Reputation: 373
The issue here was a bug within express-session package which has been addressed on github
The problem was that the req.sessionID
needs to be be a string
. So in the case of the example above, I was sending a number and in my original code I was sending a mongoDB._id
object.
The solution to the above would be to use:
req.sessionID = "1";
The solution to the real issue would have been to use:
req.sessionID = mongoDBSession._id.toString();
I hope this helps someone else with these issues at some point.
Upvotes: 1