So I'm building an app with angular on the front and nodejs/express on the backend. My problem is that when using express-session, each request creates a new session cookie.
I have searched through a lot of questions and answers but it seems that most questions that have been answered are questions regarding express 3.x, and I'm using express 4.x.
Here is the code that I am working on:
var bcrypt = require('bcrypt');
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var session = require('express-session');
var dbSchemas = require('./database-schemas.js');
var userDB = require('./UserDatabaseQuery');
var MongoDBStore = require('connect-mongodb-session')(session);
var cookieParser = require('cookie-parser');
var app = express();
var store = new MongoDBStore({
uri: 'mongodb://localhost:27017/connect_mongodb_session',
collection: 'mySessions'
});
mongoose.connect('mongodb://localhost/dbSPPM');
var db = mongoose.connection;
var Schema = mongoose.Schema;
var SALT_WORK_FACTOR = 10;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(session({
secret: 'th3s3cr3tc0d30fd00m',
cookie: {
path: '/',
maxAge: 1000 * 60 * 10
},
store: store,
resave: false,
saveUninitialized: false
}));
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With');
next();
});
app.get('/userLoggedIn', function(req, res) {
if(req.session) {
console.log('session cookie: \n' + JSON.stringify(req.session));
}
res.send({
loggedIn: req.session.username
});
})
app.post('/login', function(req, res) {
var username = req.body.data.username;
var password = req.body.data.password;
var User = mongoose.model('User', dbSchemas.userSchema);
User.findOne({username: username}, function(err, user) {
if (err) {
console.log(err);
} else {
bcrypt.compare(password, user.password, function(err, isMatching) {
if (err) {
console.log(err);
} else {
if (isMatching) {
res.send({
loggedIn: true,
session: req.session
});
} else {
res.send({
loggedIn: false,
});
return;
}
}
});
}
req.session.username = username;
console.log('created session cookie: \n' + JSON.stringify(req.session));
});
});`
When i do the console.log
i get this back:
created session cookie:
{"cookie":{"originalMaxAge":600000,"expires":"2015-10-07T11:40:34.392Z","httpOnly":true,"path":"/"},"username":"LosGlennos"}
session cookie:
{"cookie":{"originalMaxAge":600000,"expires":"2015-10-07T11:40:38.262Z","httpOnly":true,"path":"/"}}
As you can see, the get and post have created two different session cookies.
I don't actually know where I'm messing up, I have read the code so many times that variable names are starting to sound funny.
EDIT The thing I'm trying to accomplish is to get the session cookie created and view if the session for "LosGlennos" is expired.