Update session variable in Node - node.js

I set a session variable called user upon login:
req.session.authenticated_user = user;
When I set the session again later it doesn't update:
req.session.authenticated_user = somenewvalue;
This will still contain the original value of user. App module:
var session = require('express-session');
var redisStore = require('connect-redis')(session);
var redisClient = redis.createClient();
const sessionMiddleware = session({ secret: 'foo' });
app.use(session({
store: new redisStore({ client: redisClient }),
secret: 'secretsession',
resave: false,
saveUninitialized: true,
cookie: { secure: false, sameSite: true, expires: 7200000 }
}))
app.use('/users', sessionChecker, usersRouter);
My router:
var express = require('express');
var router = express.Router();
var user_controller = require('../controllers/userController')
/* GET user update. */
router.get('/user_login/login', user_controller.user_login_get);
/* POST user update. */
router.post('/user_login/login', user_controller.user_login_post);
/* GET user update. */
router.get('/:username/update', user_controller.user_update_get);
/* POST user update. */
router.post('/:username/update', user_controller.user_update_post);
How can I update a session variable in node?

Answered here: Sessions won't save in Node.js without req.session.save()
req.session won't update automatically if req is a Post request. For Post requests, one must call req.session.save() unless data is sent out through res.send, res.redirect, etc.

Related

firebase express-session dosn't store nothing in the cookies

This is my code:
const functions = require('firebase-functions');
const express = require('express');
const session = require('express-session');
const FirebaseStore = require('connect-session-firebase')(session);
const firebase = require('firebase-admin');
const cookieParser = require('cookie-parser');
const ref = firebase.initializeApp(
functions.config().firebase
);
const app = express();
app.use(cookieParser());
app.set('trust proxy', 1);
app.use(session({
store: new FirebaseStore({
database: ref.database()
}),
secret: 'abigsigrettotheseeiosnofthmbiith765huig',
resave: true,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}));
app.get('/', function(req, res, next) {
console.log(req.session);
req.session.username='xyz';
res.send('Filling the session with data');
});
app.get('/bar', function(req, res, next) {
console.log(req.session);
var sessionData = req.session.username;
res.send(`This will print the attribute I set earlier: ${sessionData}`);
});
exports.app = functions.https.onRequest(app);
When I run this, it creates new session in the DB.
And every time I refresh the page, there is a new session.
I want of course, that only one session would be created,
and that on refresh, this session would only be updated, or to get the data from there. not to create a new one every time.
Checking the cookies - showed me that no cookie is saved / created.
I've been working on this for hours...
this was frustrating when I was using firebase functions and hosting, but can be solved by simply setting name:"__session" in the session.
app.use(session({
store: new FirebaseStore({
database: ref.database()
}),
name:"__session
...

Redis not working on express-session

The code below is quite a normally snippet, but it's not working, session from request is undefined. Anyone who can give me a hint will be appreciated.
var express = require('express');
var session = require('express-session');
var redisStore = require('connect-redis')(session);
var app = express();
app.listen(3000);
app.use(session({
store: new redisStore({
host:'localhost',
port:'8543'
}),
resave: false,
saveUninitialized: true,
secret: 'somesecrettoken'
}));
app.get('/', function (req, res) {
if(req.session.isVisit) {
req.session.isVisit++;
res.send('<p>times to be here:' + req.session.isVisit + '</p>');
} else {
req.session.isVisit = 1;
res.send('1st time to be here');
}
});
A Redis client is required
var redis = require("redis"); // You can use any module to create redis client
app.use(session({
store: new redisStore({
client : redis.createClient(<your setting>)
host:'localhost',
port:'8543'
}),
resave: false,
saveUninitialized: true,
secret: 'somesecrettoken'
}));
Please refer this link:
https://www.npmjs.com/package/connect-redis
Pass the express-session store into connect-redis to create a RedisStore constructor.
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
app.use(session({
store: new RedisStore(options),
secret: 'keyboard cat'
}));

Node-Client-sessions vs express-session

I have this Node API that frontends a backend OAuth server. At the end of the SAML OAuth dance, I set the Bearer Token in a browser cookie.
// need cookieParser middleware before we can do anything with cookies
app.use(express.cookieParser());
// set a cookie
app.use(function (req, res, next) {
// check if client sent cookie
var cookie = req.cookies.cookieName;
if (cookie === undefined)
{
// no: set a new cookie
var randomNumber=Math.random().toString();
randomNumber=randomNumber.substring(2,randomNumber.length);
res.cookie('cookieName',randomNumber, { maxAge: 900000, httpOnly: true });
console.log('cookie created successfully');
}
else
{
// yes, cookie was already present
console.log('cookie exists', cookie);
}
next();
});
app.use(express.static(__dirname + '/public'));
Now I was introduced to a fancy NPM which does pretty much the same thing https://github.com/mozilla/node-client-sessions
While I was almost inclined on using this NPM, I bumped into express-session. https://github.com/expressjs/session - this is for server side sessions. But this also sets a cookie
var express = require('express');
var session = require("express-session");
var app = express();
app.use(session({
resave: true,
saveUninitialized: true,
secret: 'ABC123',
cookie: {
maxAge: 60000
}
}));
app.get("/test", function(req, res) {
req.session.user_agent = req.headers['user-agent'];
res.send("session set");
});
If my need to set only a bearer token in the browser cookie for subsequent API calls, which option should be my choice?
express-session is my go to.
If you look at what it took to accomplish the same thing with the two different methods, I think the answer is clear.
If all you want to do is set a client cookie that will enable the server to correctly authenticate future requests, express-session is awesome.
Here is an example set from another question I answered that uses MongoDB as a backend to store your sessions:
'use strict';
var express = require('express'),
session = require('express-session'),
cookieParser = require('cookie-parser'),
mongoStore = require('connect-mongo')(session),
mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/someDB');
var app = express();
var secret = 'shhh';
app.use(session({
resave: true,
saveUninitialized: true,
secret: secret,
store: new mongoStore({
mongooseConnection: mongoose.connection,
collection: 'sessions' // default
})
}));
// ROUTES, ETC.
var port = 3000;
app.listen(port, function() {
console.log('listening on port ' + port + '.')
});

how can get the current session user information in nodejs on socket event?

First of all i'm rookie with nodejs, i started to learn it about 3-4 days and i read lots of articles but they made me more confuse!
var app = express();
var expressSession = require('express-session');
var cookieParser = require('cookie-parser');
app.use(cookieParser());
app.use(expressSession({
key : 'session',
secret: 'mySecretKey',
store: sessionStore
}));
app.use(passport.initialize());
app.use(passport.session());
var server= require('http').Server(app) ;
var io = require('socket.io')(server);
var passportSocketIo = require("passport.socketio");
io.use(passportSocketIo.authorize({
cookieParser: cookieParser,
key: 'session',
secret: 'mySecretKey',
store: sessionStore,
success: onAuthorizeSuccess,
fail: onAuthorizeFail,
}));
It works great and check socket connection access, but there's a little big problem for me.
How i can access the session id on socket messages?
i want to search session data in my session store and find the current users information.
this piece of code seems not working:
io.on('connection',function(socket) {
socket.on('myevent',function(){
console.log("Session: ", socket.session);
});
});
I found
socket.request.user
It changed in new version.

How are connect-mongo MongoStore sessions actually saved?

I implemented sessions using Passport, but for storing sessions I tried connect-mongo using a mongoose connection.
This is my code (sessions part):
var express = require('express')
var mongodb = require('mongodb')
var mongoose = require('mongoose')
var bodyParser = require('body-parser')
var cookie = require('cookie-parser')
var connect = require('connect')
var passport = require('passport')
//var flash = require('connect-flash')
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var LocalStrategy = require('passport-local').Strategy;
var app = express()
var BSON = mongodb.BSONPure
app.use(express.static(__dirname+"/public"))
app.use(bodyParser())
app.use(cookie())
app.use(connect.session({ secret: 'ilovescotchscotchyscotchscotch' }));
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect('mongodb://localhost/psicologosTuxtepecDB')
var Schema = mongoose.Schema
var userCredential = new Schema({
username: String,
password: String
}, {
collection: 'members'
})
var userCredentials = mongoose.model('members', userCredential)
app.use(session({
secret: 'ziKologiia',
clear_interval: 900,
cookie: { maxAge: 2 * 60 * 60 * 1000 },
store: new MongoStore({
db : mongoose.connection.db
})
}));
Something I doubt if it would be counterproductive is that app.use(connect.session({ secret: 'ilovescotchscotchyscotchscotch' })) is usingconnect module but the MongoStore configuration is set upon a express-session variable. However, deleting first causes app to not work good (won't authenticate/redirect).
So, about my question title. Where is that session stored? I really thought I could go to my Mongo database and find any collection storing it.
How can I find such sessions at backend (Mongo) and even at the applicacion as Java Script objects?
connect-mongo stores sessions in the "sessions" collection by default. They should be there and visible in the mongo shell or any GUI tool like robomongo. Yes, it is created by default. I would pass in the mongooose_connection option instead of db.
From the docs:
mongoose_connection in the form: someMongooseDb.connections[0] to use an existing mongoose connection. (optional)
One thing you should do is replace
app.use(connect.session({ secret: 'ilovescotchscotchyscotchscotch' }));
with your
app.use(session({
secret: 'ziKologiia',
clear_interval: 900,
cookie: { maxAge: 2 * 60 * 60 * 1000 },
store: new MongoStore({
db: mongoose.connection.db
});
}));
Updated Method of MongoClient:
import session from "express-session";
import MongoStore from "connect-mongo";
app.use(
session({
secret: "Your Key",
cookie: {
maxAge: 60000 * 60 * 24, //1Sec * 1H * 24 = 1 Day
secure: process.env.NODE_ENV !== "production"? false : true
},
resave: true,
saveUninitialized: true,
store: MongoStore.create({ mongoUrl: process.env.MongoDBUrl}),
})
);

Resources