How are connect-mongo MongoStore sessions actually saved? - node.js

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}),
})
);

Related

trying to connect to Redis using typescript and nodejs

I am trying to connect to Redis using typescript and nodejs but I keep getting **
error TS2693: 'RedisStore' only refers to a type, but is being used as a value here.**
let redisCLient = createClient({legacyMode: true});
redisCLient.connect().catch(console.error);
declare module "express-session" {
interface SessionData {
isLoggedIn: boolean;
}
}
// middleware
app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use(cors());
app.use(
session({
secret: "reddit_apples_should_be_next",
resave: false,
saveUninitialized: false,
store: new RedisStore({client: redisCLient}),
})
);
You can do stuff like this
Basic Redis setup
Import statements
const express = require('express');
const session = required('express-session');
const redis = require('redis');
const connectRedis = require('connect-redis');
const app = express();
app.use(express.json());
connection
const RedisStore = connectRedis(session);
const redisClient = redis.createClient(
port: 6379,
host: 'localhost'
});
configure session middleware
app.use(session({
store: new RedisStore({client: redisClient}),
secret: 'mySecret',
saveUninitialized: false,
resave: false,
name:'sessionId',
cookie: {
//secure false for non https request , keep false in production
secure: false,
// if true, prevents client side JS from reading the cookie
httpOnly: true,
//session age in millisec // 30 mins
maxAge: 1000 * 60 * 30
}
}));

Update session variable in Node

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.

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 js Session Creating Different cookies for every request using Postgres and expression session

Here is my code
var express = require('express');
var router = express.Router();
var path = require('path');
var bodyParser = require('body-parser');
var cookieparser = require('cookie-parser');
var cors = require('cors');
var session = require('express-session');
var PostgreSqlStore = require('connect-pg-simple')(session);
//var mongoose=require('mongoose');
var app = express();
app.use(bodyParser());
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
//session starts
app.use(cookieparser());
var sessionOptions = {
secret: "secret",
resave: true,
//cookie :{ maxAge : 30 * 24 * 60 * 60 * 1000},
cookie: { httpOnly: false },
saveUninitialized: false,
store: new PostgreSqlStore({
conString: "postgres://postgres:password#127.0.0.1:5432/session"
})
};
app.use(session(sessionOptions));
//session ends
require('./routes/routes.js')(app);
app.listen(4001);
//exports.start = start;
exports.app = app;
While inserting on login
req.session('userid')=email;
the database has one record , but for next request it inserts another cookie record . I want to make it only once for authentication purpose. and i want to know better way of simple auth using postgres.

Session id being same for different client Nodejs

Currently we are setting up session in the cookie using express-session with passport.js and connect-redis to store the data in redis.
I have multiple node server serving requests. For each request without a session, I am creating a new session. Sometimes, an existing session id is being assigned to a new request. Before creating a unique session, I am checking whether the cookie is there...if it is, then I am not creating a new session. But while doing so, we are seeing that same session id being shared with different client.
How do I know its being same?
First user tries to login, it gives successful login and sets up the session and gives the correct information about the user profile.
Second user tries to login, it gives a successful login but sets the session as the previous i.e. first user's session , hence the second user sees the first user info in the profile section.
Code for the Session implementation:
function sessionImplementation() {
return function (req, res, next) {
if(/ucompany=s%3A/.test(req.headers['cookie'])){
var cookie = req.headers['cookie'].split("ucompany=s%3A");
var zCookie = cookie[1].split(".");
var genid = zCookie[0];
return session({
genid:function () {
return genid;
},
store: redis,
cookie: {
maxAge: new Date(Date.now() + (7 * 24 * 60 * 60 * 1000))
},
secret: 'ucomp123',
resave: false,
name: "ucompany",
saveUninitialized: true
})(req, res, next)
}
return session({
store: redis,
cookie: {
maxAge: new Date(Date.now() + (7 * 24 * 60 * 60 * 1000))
},
secret: 'ucomp123',
resave: false,
name: "ucompany",
saveUninitialized: true
})(req, res, next)
}
}
What is the issue and how can I fix it?
Update 1
As per #robertklep I have modified my code.
var express = require('express');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
var app = express();
app.use(bodyParser.json());// to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ extended: false }));
app.use(compress());
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//app.use(cookieParser());
var redis = new RedisStore({
host:config.redis.url,
port:config.redis.port,
prefix:'sess-'+new Date().getDate()+'-'+(new Date().getMonth()+1)+'-'+new Date().getFullYear()+':'
});
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
store: redis,
cookie: {
expires: new Date(Date.now() + (7 * 24 * 60 * 60 * 1000)),
maxAge:7 * 24 * 60 * 60 * 1000
},
secret: 'ucomp123',
resave: false,
name: "ucomapny",
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
There are several issues with your code:
instead of letting express-session handle the session cookies, you're trying to handle them yourself;
you're instantiating the session middleware for every single request, which is a waste of resources and may also cause problems (I haven't dug into express-session deep enough to make any definitive claims on that);
maxAge (for the cookie) should not be a date but a number (the number of milliseconds from now that the cookie should remain valid); you're confusing it with expires, which is used to set a point-in-time;
The regular way of using it looks like this:
var session = require('express-session');
var express = require('express');
var app = express();
...
app.use(session({
store : redis,
cookie : { maxAge : 7 * 24 * 60 * 60 * 1000 },
secret : 'ucomp123',
name : 'ucompany',
resave : false,
saveUninitialized : true
});
where is a genid ?
you have to generate it yourself. Use uuid package

Resources