Express Session lose data before cookie expires - node.js

I'm using express-session with redis in my NodeJS Backend.
let redisClient = redis.createClient(6380, process.env.REDISCACHEHOSTNAME, {auth_pass: process.env.REDISCACHEKEY, tls: {servername: process.env.REDISCACHEHOSTNAME}});
app.use(session({
store: new RedisStore({ client: redisClient }),
saveUninitialized: false,
secret: process.env.secret,
resave: true,
cookie: {
maxAge: 1 * 1 * 60 * 60 * 1000
}
}));
On login I store some user details in the session:
req.session.user = result;
And I build a middleware, which log my current session and refresh it on each request:
isOnline = (req, res, next) => {
console.log(req.session);
if (!req.session.user) {
return res.status(401).json({ result: 'Keine Session vorhanden', status: 'failure' });
}
req.session.touch();
next();
};
The extending of my cookie is working well. The cookie expiration datetime is everytime reset to 60 minutes from the request time. Which I can see by the console.log:
Session {
cookie: {
path: '/',
_expires: 2022-03-07T18:46:30.727Z,
originalMaxAge: 120000,
httpOnly: true
},
user: { ... }
}
The issue is, that my user data are lost after 60 minutes. So the cookie itself refreshs, but not the data. So how I can avoid this?

Related

Why express session sometimes does and sometimes doesn't make cookies?

I am using cookies like this on my express server :
app.use(
session({
secret: "someStringForSecretKey",
resave: false,
store: new redisstore({ client: RL }),
saveUninitialized: false,
cookie: {
maxAge: 1000 * 60 * 60 * 24,
httpOnly: true,
secure: true,
sameSite: "none",
},
})
);
and sending back the data via axios like this :
axios.defaults.withCredentials = true;
axios.post(`${import.meta.env.VITE_HOSTNAME}/auth`, {
username: userRef.current.value,
password: passwordRef.current.value,
}).then(function (response) .......
I am setting the session as such :
req.session.user = req.body.username;
req.session.save(()=>{
if(req.session.user ){
res.status(200).json({
foo : true
});
}
Now to my surprise the cookie is sometimes set and sometimes isn't. There is no pattern.
Why express session sometimes does and sometimes doesn't make cookies?
httpOnly: true,
Creates undesirable behavior in which it sometimes creates the cookie and sometimes doesn't.
httpOnly: false,
Solved the issue.

Persist expired session data into new session in express js

const adminSession = session({
secret: process.env.ADMIN_SECRET,
resave: false,
saveUninitialized: false,
store: sessionStore,
name: "adminSession",
cookie: {
maxAge: 600000,
secure: false,
},
});
app.use(adminSession());
app.get("/sessionViews", function (req, res, next) {
if (req.session.views) {
req.session.views++;
res.send(`Number of view: ${req.session.vies}`);
} else {
req.session.views = 1;
res.send(" No views");
}
});
Here after the session is expired, req.session.views value is also gone. And new session will be generated with req.session.views=0.
That's how we create the number of views in the certain page, isn't it?
How to keep value persistent with another session?

Express-session with MySQL storage does not save user

I'm using express-session for handling user session in Node.js application. The problem is after rewriting it for MySQL storage it seems like after changing route all information disappears and my middleware redirects me for login page again.
My code:
let options = {
host: "localhost",
user: "root",
port: 3306,
password: "",
database: "cursova"
}
var sessionStore = new MySQLStore(options, con);
app.use(session({
key: 'myCookie',
secret: 'secret12345',
store: sessionStore,
resave: false,
saveUninitialized: false,
cookie: {
originalMaxAge: 1000 * 60 * 5,
maxAge: 60000 * 5,
secure: true,
path: '/',
}
}));
console results:
Try initializing the session:
app.use((req, res, next) => {
req.session.init = "init";
next();
});
For session, I have this:
const options = {
host: config.db.host,
port: config.db.port,
user: config.db.user,
password: config.db.password,
database: config.db.database
};
const sessionStore = new MySQLStore(options);
const expiryDate = new Date(Date.now() + 24 * 60 * 60 * 1000); // 1 hour
app.use(session({
store: sessionStore,
secret: process.env.SESSIONSECRET,
resave: false,
saveUninitialized: false,
cookie: {
//secure: true,
//httpOnly: true,
expires: expiryDate
}
}));
I am not passing the connection and do not have a key. I add in the HTTP and secure once I know it works.
Most likely the issue is because of "secure: true" from cookie. This means the cookie is saved only if you use HTTPS. Try setting it to false

nodejs session cookie browser storage

Server is nodejs with express-session, passport, express
I want to avoid saving a cookie when the user is not authenticated, is this possible?
var sessionStore = new session.MemoryStore;
app.use(session({
cookie: { maxAge: null,
httpOnly: true,
secure: true,
},
store: sessionStore,
resave: 'false',
secret: 'somthing',
name: "id",
saveUninitialized: false
}));
Is it somehow possible to only store the cookie when the user did successfully login? Thanks!
You have to create an express-session: https://www.npmjs.com/package/express-sessions
and then store the session like this:
let session = require("express-session");
app.use(session({
secret: "secret",
resave: false,
saveUninitialized: true,
cookie: {secure: true,
httpOnly: true,
maxAge: 1000 * 60 * 60 * 24
}
}));
This session will be stored during your visit on the webpage. If you want to set values to the cookie, simply request the cookie in a request and set somekind of value:
router.route("/login")
.post(function(req, res) {
req.session.Auth = req.body.user // => user values?
})
OR
You can use cookie-session(https://www.npmjs.com/package/cookie-session)
If you use cookie session then if you made any changes to session variable or from server side, then no need to restart server.
app.use(cookieSession({
name: 'session',
keys: ['key1', 'key2']
}))
app.get('/', function (req, res, next) {
// Update views
req.session.views = (req.session.views || 0) + 1
// Write response
res.end(req.session.views + ' views')
})

access session from different port in same IP NodeJs

I have 2 web application in same IP and different port:
app1 = (site.com) -> 66.88.66.88:5000
app2 = (login.site.com) -> 66.88.66.88:5001
I`m using Nginx and set 2 proxy for these 2 application. The users have to login in to app1 and system will set a session for logged in user. after that system will redirect user to app2 and I need access to logged in user session in appp2.
I store my session in mongodb in same collecton that both apps has access to that.
My problem is I can`t have access to loggedin user session in app2.
This is my session settings:
app1:
const MongoStore = require('connect-mongo')(session);
mongoose.Promise = require('bluebird');
const connection = mongoose.createConnection(config.dbhost, function(err){
if(err){
console.log(err);
} else {
console.log('connected to the database successfuly.');
}
});
/* Session config */
var expiryDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) // 7 days
app.use(session({
secret: config.secureHasherKey ,
resave: true,
saveUninitialized: false,
cookie: {
secure: false,
httpOnly: true,
domain: 'site.com',
path: '/',
expires: expiryDate
},
store: new MongoStore({ mongooseConnection: connection })
}));
app2:
const MongoStore = require('connect-mongo')(session);
mongoose.Promise = require('bluebird');
const connection = mongoose.createConnection(config.dbhost, function(err){
if(err){
console.log(err);
} else {
console.log('connected to the database successfuly.');
}
});
/* Session config */
var expiryDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) // 7 days
app.use(session({
secret: config.secureHasherKey ,
resave: true,
saveUninitialized: false,
cookie: {
secure: false,
httpOnly: true,
domain: 'login.site.com',
path: '/',
expires: expiryDate
},
store: new MongoStore({ mongooseConnection: connection })
}));
And this is my CORS settings:
app.all("*", function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma,
Origin, Authorization, Content-Type, X-Requested-With");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
return next();
});
How can I find the problem?

Resources