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?
Related
I have this logout route with expressJS using express-session :
router.post('/logout', (req, res) => {
req.session.user = null;
req.session.destroy((err) => {
if (err) {
return res.status(400).end();
} else {
return res.status(200).end();
}
});
});
Although the user is logged out Correctly and the sid changes, The cookie still exists!! which freaking me out.
I want to completely remove the cookie to calm my heart.
This is the config of the express-session package
app.use(
session({
store: new MariaDBStore({
pool: require('./config/db_pool')
}),
name: 'sid',
secret: process.env.KEY,
saveUninitialized: false,
resave: false,
cookie: {
path: '/',
httpOnly: true,
secure: process.env.NODE_ENV === 'development' ? false : true
}
})
);
I git the answer from #Joe comment above and this like
Answer from here
using this close completely removes the cookie.
the options of res.clearCookie are not optional .
res.clearCookie('sid', { path: '/' });
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?
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')
})
I need to terminate the user session or log user out when they close the browser or tab.
Following is the code implemented to maintain session:
app.use(session({
store: new RedisStore({
url: REDIS_CONNECTION_URL,
}),
secret: 'COOKIE_SECRET',
name: 'COOKIE_NAME',
resave: true,
saveUninitialized: false,
rolling: true,
cookie: {
path: '/',
httpOnly: true,
maxAge: 'COOKIE_TIMEOUT',
},
}));
I have tried setting cookie.expires to true but that doesn't help.
You have to handler onclose event of client user, then call a http request to destroy client's session on server side.
Client side:
$(window).unload(function () {
$.get('/session/destroy');
});
Server side:
app.get('/session/destroy', function(req, res) {
req.session.destroy();
res.status(200).send('ok');
});
I have inherited a Express site which needs some updating. There is a route for resetting password, but I need to invalidate all the users sessions when this happen and allow for auto login on the current browser at the same time.
I'm kinda new to Express, so can anybody point me in the direction of a guide?
Setting up of sessionStore:
const sessionStore = knexSession(session)
const store = new sessionStore({
knex: db
})
app.use(session({
secret: sessionKey,
resave: false,
saveUninitialized: false,
store,
cookie: {
maxAge: null,
httpOnly: true,
secure: app.get('env') !== 'development' || app.get('port') === 443,
}
}))
Resetting password:
let data = {
password,
token: null,
expires: null
}
return models.user.update(user.id, user.id, data)
.then(_ => {
//reset session user sessions
//only invalidates the current session
req.logout()
req.session.destroy(function (err) {
res.clearCookie('connect.sid')
res.redirect('/')
});
})