SessionID is generating a unique value on every post request - node.js

I am trying to identify the user that is on my application via sessionId, not actual info on the user account itself. However, what I am noticing is that the sessionId changes everytime the user performs an action on the page. As shown below. My goal would be to have the same sessionID from the point they open the webpage until they close it.
const app = require('express')();
const https = require('https');
const fs = require('fs');
const session = require('express-session');
function getDateTimestamp(){
var today = new Date();
var date = today.getFullYear()+'_'+(today.getMonth()+1)+'_'+today.getDate();
return date;
}
app.use(session({
resave: false,
saveUninitialized: true,
secret: 'whatever',
cookie: {
maxAge: 60*60*1000,
sameSite: true
}
}))
app.get('/', (req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
var readStream = fs.createReadStream('index.html','utf8');
readStream.pipe(res);
});
app.post('/:fieldName/:flag/:time/:dashboard/:identifier/:user', (req, res) => {
console.log('POST message received', req.params);
if (req.params && req.params.fieldName) {
fs.appendFileSync(`./changeLog_${getDateTimestamp()}.csv`, `${req.params.fieldName},${req.params.flag},${req.params.time},${req.params.dashboard},${req.params.identifier},${req.params.user},${req.sessionID}\n`);
return res.send('OK')
}
res.status(400).end()
});
Client Side
function onParameterChange (parameterChangeEvent) {
parameterChangeEvent.getParameterAsync().then(function (param) {
parameterIndicator = 'Parameter'
const details = {
method: 'POST',
credentials: 'include'
//body: JSON.stringify(data),
// headers: {
// 'Content-Type': 'application/json'
// }
};
fetch(`url/${param.name}/${parameterIndicator}/${getDateTimestamp()}/${dashboardName}/${param.name}/${worksheetData}`, details).then((res) => {console.log(res);});
});
}
Here is my output showing a different session for the same user.

Just to illustrate my comment above, I actually have ran a quick test with a simple setup, and toggling saveUninitialized actually seems to make the difference:
// app.js
const express = require('express')
const app = express()
const session = require('express-session')
// Run the file as "node app false" or "node app true" to toggle saveUninitialized.
const saveUninitialized = process.argv[2] == "true" ? true : false
app.use(session({
resave: false,
saveUninitialized,
secret: 'whatever',
cookie: {
maxAge: 60 * 60 * 1000,
sameSite: true
}
}))
app.get("/", (req, res) => {
res.status(200).send(req.sessionID)
})
app.listen(3000, () => {
console.log('server started on http://localhost:3000')
})
// Response body
node app false
// 1st request: OTnFJD-r1MdiEc_8KNwzNES84Z0z1kp2
// 2nd request: 5UVVGng_G72Vmb5qvTdglCn9o9A4N-F6
// 3rd request: 9aGsAwnHh1p1sgINa1fMBXl-oRKcaQjM
node app true
// 1st request: StUrtHOKBFLSvl5qoFai6OQCm7TY87U-
// 2nd request: StUrtHOKBFLSvl5qoFai6OQCm7TY87U-
// 3rd request: StUrtHOKBFLSvl5qoFai6OQCm7TY87U-
But maybe there is more to it than that with your setup.

Related

`req.session.user` is `undefined` when using `express-session` and `connect-mongo`

I've created a react app that runs on port:3000 and an express app that runs on port:3001.
I am using express-session and connect-mongo to handle user sessions. When I set a user session in /login it was recorded in MongoDB as expected. But when I query for req.session.user later in a different path/route, for example /channels it returns undefined.
This is how my app.js looks
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const {Server} = require("socket.io");
const io = new Server(server);
const port = process.env.PORT || 3001;
const cors = require("cors");
const path = require('path');
const session = require('express-session');
const bodyParser = require('body-parser');
const oneDay = 1000 * 60 * 60 * 24;
const MongoStore = require('connect-mongo');
const md5 = require('md5');
const hash = '=:>q(g,JhR`CK|acXbsDd*pR{/x7?~0o%?9|]AZW[p:VZ(hR%$A5ep ib.&BLo]g';
app.use(session({
secret: hash,
saveUninitialized: false,
resave: false,
store: MongoStore.create({
mongoUrl: 'mongodb://localhost:27017/chat',
ttl: 14 * 24 * 60 * 60 // = 14 days. Default
})
}));
app.use(
cors({
origin: true,
credentials: true,
optionsSuccessStatus: 200
}));
// create application/json parser
const jsonParser = bodyParser.json({limit: '50mb'})
// create application/x-www-form-urlencoded parser
const urlencodedParser = bodyParser.urlencoded({limit: '50mb', extended: false})
app.post('/login', jsonParser, (req, res) => {
db.users.find({email: req.body.email}).toArray().then(user => {
if (user.length < 1) {
res.send({success: false, error: 'NOT_FOUND', message: 'Invalid login info!'});
} else {
user = user[0];
if (user.password === req.body.password) {
db.users.updateOne({"email": user.email}, {$set: {"online": "1"}}).then(ret => {
req.session.user = user.email;
req.session.userdata = user;
res.json(<=user data=>);
});
}
}
})
});
app.post('/channels', async (req, res) => {
if (!req.session.user) {// THIS IS ALWAYS TRUE; EVEN AFTER SUCCESSFUL LOGIN
res.json({logout: true});
return;
}
const user = JSON.parse(req.session.userdata);
const channels = db.channels.find({contacts: {$all: [user._id]}}).toArray().then(channels => {
let allch = {};
channels.map(function (channel) {
channel.id = channel._id.toString();
channel.notif = 0;
allch[channel.id] = channel;
});
res.json(allch);
});
});
When You fetch from front-end for specific route, don't forget to include in options: "credentials: "include" ", like here:
const options = {
method: "POST",
headers: {
"content-type": "application/json",
},
body: JSON.stringify(searchInput),
credentials: "include",
};
fetch("http://localhost:4000/sendSearchInput", options)
.then((res) => res.json())
.then((data) => {
console.log(data);
});
Edit:
Note - This should be included in each request from the client that either sets or reads the 'express-session' middleware (req.session.x).
(Not just reads)
I think you will need to call req.session.save() yourself when you want to update the session store with the current data.

Express Session sending new session for every request in production server

I have been developing a simple login system and trying to deploy it on a production server. The express session works perfectly fine in localhost but when it comes to the production server or cross-origin it sends a new session in every request.
Server Codes:
const express = require('express');
const app = express();
const path = require('path');
const mysql = require('mysql');
const session = require('express-session');
const MySQLStore = require('express-mysql-session')(session);
const bcrypt = require('bcryptjs');
require('dotenv').config();
const cors=require("cors");
const bodyparser = require("body-parser")
app.use(express.json())
app.use(bodyparser.urlencoded({extended: true}))
app.use(express.static(path.join(__dirname, 'public')));
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
var db = mysql.createConnection({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASS,
database: process.env.DATABASE_NAME
});
db.connect((err) => {
if(err) {
console.log('error when connecting to db: ', err);
throw err;
}
});
const sessionStore = new MySQLStore({
expiration : (365 * 60 * 60 * 24 * 1000),
endConnectionOnClose: false,
}, db);
app.use(session({
key: 'fsasfsfafawfrhykuytjdafapsovapjv32fq',
secret: 'abc2idnoin2^*(doaiwu',
store: sessionStore,
resave: false,
saveUninitialized: false,
cookie: {
maxAge: (365 * 86400 * 1000),
httpOnly: false,
secure: false,
sameSite: 'none'
}
}));
app.post('/isLoggedIn', (req, res)=>{
// req.session.destroy();
if(req.session.userID || req.session.userID == 0) {
let cols = [req.session.userID];
db.query('SELECT * FROM user WHERE user_id = ? LIMIT 1',cols, (err, data, fields) => {
if(data && data.length === 1) {
res.json({
success: true,
first_name: data[0].first_name,
email: data[0].email,
type:data[0].type,
});
return true;
}else {
res.json({
success: false,
});
}
});
}else {
res.json({
success: false
})
}
});
API request:
let res = await fetch("https://hotel-network-manager1.herokuapp.com/isLoggedIn", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
credentials: 'include',
mode:'cors'
});
I have read many posts and documentation but couldn't solve the issue. You can even check the server running in Heroku in the above URL of the fetch API. When using this same server running on the localhost it works perfectly fine which means this has something to do with CORS. Does anyone has any idea what I'm missing here.

Openlitespeed Session Timeout after 1 min idle with Nextjs App

Hello Stackoverflow Community.
So I am encountering a very weird problem when hosting my nextjs powered by express with openlitespeed. Everything works great in production, except one thing - the authentification of sessions. The user is saved in the cookies correctly and it works if you are not idle for more than a minute on the page you are on, but if you are idle for more than a minute, then the request is not authenticated anymore even though the cookie is still there.
I am using redis for my cookie store, and everything works in local testing, where openlitespeed is not present. The authentification I am using is passportjs with express-session. Have any of you encountered this problem, and if so, how did you solve it?
I have tried disabling the cache module, set all timeouts to a higher value or disabling them, use different memorystores and more, but no luck. Here is the server.js file, however, I do not believe it has something to do with the code itself, but rather the config of openlitespeed:
const express = require('express')
const next = require('next')
const passport = require('passport');
const redis = require('redis')
const session = require('express-session')
const {v4: uuidv4} = require('uuid');
const path = require('path');
const log = require('./logger')
let RedisStore = require('connect-redis')(session)
let redisClient = redis.createClient()
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
//Json parsing
server.use(express.json());
server.use(express.urlencoded({extended: true}));
if (dev){
//Express session
server.use(session({
store: new RedisStore({ client: redisClient }),
genid: function() {
return uuidv4()},
secret: uuidv4(),
resave: false,
saveUninitialized: false,
cookie: {
secure: false,
maxAge: 86400000
}
}))
}
else{
//Express session
server.use(session({
store: new RedisStore({ client: redisClient }),
genid: function() {
return uuidv4()},
secret: uuidv4(),
proxy: true,
resave: false,
saveUninitialized: false,
cookie: {
secure: true,
maxAge: 86400000
}
}))
}
//Passport auth
server.use(passport.initialize());
server.use(passport.session());
//Import of the passport config
const initializePassport = require('./passport-config');
initializePassport(passport);
//Login route
server.post('/login', passport.authenticate('login'), (req, res) => {
res.send({message: 'Successful login', login: true})
});
const passportLogout = function (req, res, next) {
req.logout()
next()
}
//Logout route
server.get('/logout', passportLogout, (req, res) => {
req.session.destroy();
res.redirect('/login');
});
//Import registrerings route. Pga. brugen af route i stedet for app kan vi bruge denne middleware med en anden underside, hvis vi f.eks. ville gøre så admins også kunne lave brugere.
const registerRoute = require('./routes/register-user');
server.use('/register', registerRoute);
//User routes hvor login er required. Rendering. Skal stå under called til initializepassport, ellers kan den ikke finde ud af at den er authenticated via passport, og auth.js returnerer dig derfor til login
const usersRoutes = require('./routes/user/user-routes');
server.use(usersRoutes);
//Admin routes til rendering
const adminRoutes = require('./routes/admin/admin-routes');
server.use(adminRoutes);
const indexRoutes = require('./routes/index-routes');
server.use(indexRoutes);
server.all('*', (req, res) => {
return handle(req, res)
})
server.listen(port, (err) => {
if (err) throw err
log.logger.log({
level: "info",
message: `Server was started on ${port}`,
additional: "properties",
are: "passed along",
});
console.log(`> Ready on http://localhost:${port}`)
})
})
All right, so I figured it out finally. The configuration for Openlitespeed was set, so that it could create as many httpd workers as it wants. Therefore, when a new was created and the requests went over to that one, it seems the authentification did not stick. I have fixed this by setting the "Number of Workers" to 1 under Server Configuration -> Server Process -> Number of Workers.
As for my server.js file I used to setup nextjs and openlitespeed:
const express = require("express");
const next = require("next");
const passport = require("passport");
const redis = require("redis");
const session = require("express-session");
const { v4: uuidv4 } = require("uuid");
const path = require("path");
const log = require("./logger");
let RedisStore = require("connect-redis")(session);
let redisClient = redis.createClient({ auth_pass: process.env.DB_PASSWORD });
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
//Json parsing
server.use(express.json());
server.use(express.urlencoded({ extended: true }));
if (dev) {
//Express session
server.use(
session({
store: new RedisStore({ client: redisClient }),
genid: function () {
return uuidv4();
},
secret: uuidv4(),
resave: false,
saveUninitialized: false,
cookie: {
secure: false,
maxAge: 86400000,
},
})
);
} else {
//Express session
server.use(
session({
store: new RedisStore({ client: redisClient }),
genid: function () {
return uuidv4();
},
secret: uuidv4(),
proxy: true,
resave: false,
saveUninitialized: false,
cookie: {
secure: true,
maxAge: 86400000,
},
})
);
}
//Passport auth
server.use(passport.initialize());
server.use(passport.session());
//Import of the passport config
const initializePassport = require("./passport-config");
initializePassport(passport);
//Login route
server.post("/login", passport.authenticate("login"), (req, res) => {
res.send({ message: "Successful login", login: true });
});
const passportLogout = function (req, res, next) {
req.logout();
next();
};
//Logout route
server.get("/logout", passportLogout, (req, res) => {
req.session.destroy();
res.redirect("/login");
});
//Import registrerings route. Pga. brugen af route i stedet for app kan vi bruge denne middleware med en anden underside, hvis vi f.eks. ville gøre så admins også kunne lave brugere.
const registerRoute = require("./routes/register-user");
server.use("/register", registerRoute);
//User routes hvor login er required. Rendering. Skal stå under called til initializepassport, ellers kan den ikke finde ud af at den er authenticated via passport, og auth.js returnerer dig derfor til login
const usersRoutes = require("./routes/user/user-routes");
server.use(usersRoutes);
//Admin routes til rendering
const adminRoutes = require("./routes/admin/admin-routes");
server.use(adminRoutes);
const indexRoutes = require("./routes/index-routes");
server.use(indexRoutes);
server.all("*", (req, res) => {
return handle(req, res);
});
server.listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on ${port}`);
});
});

Session token isn't storing and isn't viewable from browser

I'm trying to setup a session storage of a userID for an app im working on and I cannot for the life of me get express-session to work.
I've checked out a ton of stack overflow posts, tutorials, and other websites and followed all of the instructions there to no avail. The cookie doesn't even appear in the browser. I've tried changing the order of the .use as well and no other location worked.
Here's the code
const session = require('express-session');
const cookieParser = require('cookie-parser');
const App = require('./app');
var app = new App();
const server = express();
const port = process.env.PORT || 3030;
server.use(cors());
server.use(express.static(path.join(__dirname, buildPath)));
server.use(cookieParser());
server.use(session({
key: 'user_sid',
secret: 'somerandonstuffs',
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 10000,
secure: false,
ttpOnly: false
}
}));
server.use((req, res, next) => {
console.log(req.cookies);
console.log(req.session);
if (req.cookies.user_sid && !req.session.user) {
res.clearCookie('user_sid');
}
next();
});
server.get('/api/userRole', async (req, res, next) => {
try {
const role = await app.userRole(req.query.userID, req.query.email);
res.send({ role });
req.session.user = req.query.userID; //assign
}
catch (error) {
next(error);
}
});
server.get('/api/music', async (req, res, next) => {
try {
console.log(req.session.user) //returns undefined
const uid = req.query.user;
app.checkAuth(uid, app.constants.roles.member);
const music = await app.music(req.query.status);
res.send(music);
}
catch (error) {
next(error);
}
});
And here is the result from the console logs
{}
Session {
cookie:
{ path: '/',
_expires: 2019-07-19T22:01:58.342Z,
originalMaxAge: 10000,
httpOnly: false,
secure: false } }
{}
Session {
cookie:
{ path: '/',
_expires: 2019-07-19T22:01:58.387Z,
originalMaxAge: 10000,
httpOnly: false,
secure: false } }
undefined
All I can seem to get as a response is undefined. Any idea what might be going wrong? Thanks in advance for any help.
You need to set up a storage option for express-session. The easiest one to set up is session-file-store, but I'd recommend using something like connect-redis for a production environment.
You then pass the session storage instance to the express-session options like this:
var session = require('express-session');
var FileStore = require('session-file-store')(session);
var fileStoreOptions = {};
app.use(session({
store: new FileStore(fileStoreOptions),
secret: 'keyboard cat'
}));

New Session ID when Using Isomorphic Fetch

I have an unexpected behavior when using isomorphic-fetch vs. request-promise related to Express sessions (and Express session ID in particular):
As part of the troubleshooting process, I implemented two methods in client.js for calling endpoints in server.js: 1) isomorphic-fetch, and 2) request-promise.
Client.js
// Method 1: isomorphic-fetch
require('es6-promise').polyfill();
require('isomorphic-fetch');
fetch('http://localhost:3000', {
credentials: 'same-origin',
})
.then(function(response) {
console.log(response.status);
});
fetch('http://localhost:3000', {
credentials: 'same-origin',
})
.then(function(response) {
console.log(response.status);
});
// Method 2: request-promise
var rp = require('request-promise').defaults({
jar: true
});
function requestPage() {
return rp('http://localhost:3000/');
}
requestPage()
.then(console.dir)
.then(requestPage)
.then(console.dir)
.catch(console.error);
Server.js
var app = require('express')();
app.use(require('morgan')('dev'));
var session = require('express-session');
var FileStore = require('session-file-store')(session);
app.use(session({
name: 'server-session-cookie-id',
secret: 'my express secret',
saveUninitialized: true,
resave: true,
store: new FileStore(),
cookie: {
secure: false
}
}));
app.get('/', function initViewsCount(req, res, next) {
console.log('req.session.id = ' + req.session.id);
if (typeof req.session.views === 'undefined') {
req.session.views = 1;
return res.end('Welcome to the file session demo. Refresh page!');
}
return next();
});
app.get('/', function incrementViewsCount(req, res, next) {
console.assert(typeof req.session.views === 'number',
'missing views count in the session', req.session);
req.session.views++;
return next();
})
app.use(function printSession(req, res, next) {
console.log('req.session', req.session);
return next();
});
app.get('/', function sendPageWithCounter(req, res) {
res.setHeader('Content-Type', 'text/html');
res.write('<p>views: ' + req.session.views + '</p>\n');
res.end();
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
When I execute node client.js, here is the output of the server:
req.session.id = deWKCvqcyGiAvVSUvHv2Db7sjvE7xN1E
req.session.id = MxLHWjbMMvV4GRfPSf6sQ12XvauiJJot
req.session.id = A3KTLMdBopQ7pAfcTsJhnzzdokdA7hGI
GET / 200 1.407 ms - -
GET / 200 7.625 ms - -
GET / 200 0.728 ms - -
req.session.id = A3KTLMdBopQ7pAfcTsJhnzzdokdA7hGI
req.session Session {
cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true,
secure: false },
views: 2,
__lastAccess: 1517449125197 }
GET / 200 6.902 ms - -
I confirmed that method 2 (request-promise) successfully persists the session on the server. In other words, session A3KTLMdBopQ7pAfcTsJhnzzdokdA7hGI is associated with this method.
However, as observed from the output, method 1 (isomorphic-fetch) generates two separate sessions on the server.
Question: Why does isomorphic-fetch create two separate sessions on the server?
Troubleshooting performed:
I replaced localhost with 127.0.0.1, but this did not change the behavior.
I replaced same-origin with include, but this did not change the behavior.
Environment:
node v6.10.3
isomorphic-fetch 2.2.1
request-promise 4.2.2

Resources