How to create a session for user system in node.js - node.js

I am trying to create a session for my system of users but I do not manage in any way to implement the sessions and it returns me that they are not defined.
I am currently using express-session, body-parser and cookie-parser.
I have tried to implement the session variables from my app.js file, invoke it to my access file and I still get an error of variable without defining
my varaibles of app.js
app.use(cookieParser());
const redis = new connectRedis(session);
app.use(session({ store : new redis, saveUninitialized: true, resave: true, secret: 'it*SFVse', ttl : 3600, cookie: { maxAge: 3600000 * 24 * 7 } }));
app.use(connectFlash());
my post form
if (bcrypt.compareSync(password, result[0].password)) {
message = 'Welcome';
req.session.user = 1;
res.render('index.ejs', {
message,
title: "Login",
});
}
my index.js
getIndex: (req, res) => {
if (typeof req.session.user === 'undefined') { session = 'no session' } else { session = "session"; }
res.render('index.ejs', {
title: "Login",
message: '',
session
});
}
TypeError: Assignment to constant variable.

Related

Session data still not persistent between routes, even though session management is done via connect-mongo in MongoDB

Even though I let MongoStore handle my sessions, my sessions are still undefined when I try to access sessions from a different api route.
For example in my /login route:
app.route("/login")
.post(async (req, res) => {
var username = req.body.username,
password = req.body.password;
console.log('\t#/login');
try {
var user = await User.findOne({ username: username }).exec();
if (!user) {
res.redirect("/login");
}
user.comparePassword(password, (error, match) => {
if (!match) {
console.log('redirecting to /login')
res.redirect("/login");
}
});
req.session.user_sid = {user};
console.log('\treq.session:');
console.log(req.session) // output screenshot provided below
} catch (error) {
console.log(error)
}
});
And it outputs as:
However, when I try to access the req.session from my /dashboard route, I get undefined. The /login route and its corresponding log is below:
app.get("/dashboard", (req, res) => {
console.log("\t#/dashboard route:")
console.log("\treq.session:");
console.log(req.session); // session is undefined even though it wasnt in my login route
if (req.session.user && req.cookies.user_sid) {
// res.sendFile(__dirname + "/public/dashboard.html");
console.log(req.session);
res.send("send something")
} else {
res.send("go back to /login");
}
});
I let mongo manage my sessions like:
const MongoStore = require("connect-mongo");
app.use(session({
secret: 'mysecret',
resave: false,
store: MongoStore.create({
mongoUrl: sessionDbUrl,
collection: 'sessions',
ttl : 14 * 24 * 60 * 60, // 14 days
}),
// store: new MongoStore({ mongooseConnection: db }),
saveUninitialized: true,
cookie: { maxAge: 1000 * 60 * 60 * 24, secure: true }, // 24 hours
}));
My problem is that the session do not persist within my routes, even though I tried Mongo. When I let mongo handle my sessions, does these sessions get stored in Mongo that I can view in Compass? My understanding is that, session management done via mongodb simply makes sessions data persistent throughout the app without actually needing to store the sessions as collections in the database. Please correct my understanding if I'm wrong, I've been stuck on this for days. TIA

CSRF with fastify session cookies

I have a fastify session plugin that creates user sessions and manages them in postgres, but i want to make sure that i have all my sessions protected from CSRF. Im looking at the fastify-csrf plugin and im not exactly sure how to properly implement this. Do i need to generate the csrf token only when the session cookie is first generated or on all requests?
session plugin:
const cookie = require('fastify-cookie');
const session = require('fastify-session');
const csrf = require('fastify-csrf');
const pgSession = require('connect-pg-simple')(session);
const fp = require('fastify-plugin');
/**
* #param {import('fastify').FastifyInstance} fastify
*/
const plugin = async (fastify) => {
// All plugin data here is global to fastify.
fastify.register(cookie);
fastify.register(csrf, { sessionPlugin: 'fastify-session' });
fastify.register(session, {
store: new pgSession({
conString: process.env.DATABASE_URL,
tableName: 'user_session', // Defaults to 'session'
}),
secret: process.env.SESSION_SECRET,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: process.env.NODE_ENV !== 'development',
maxAge: 86400 * 1000, // 1 day expiration time
},
});
<!-- This is from the documentation, should this only be applied to the /login route when the cookie is generated? When do i verify that the cookie has not been tampered with?
fastify.route({
method: 'GET',
path: '/',
handler: async (req, reply) => {
const token = await reply.generateCsrf();
return { token };
},
});
// Add the user object to the session for later use.
fastify.addHook('preHandler', (req, reply, next) => {
if (!req.session) req.session.user = {};
next();
});
};
module.exports = fp(plugin);

How to create a node.js session with express?

i am using nodejs and mongodb, the problem is that my express session doesn't work
Frontend code:
$(document).on('click', "#signin", function(){
$.ajax({
type: "POST",
url: "/conectare",
data: {username: $(".username").val(), password: $(".password").val()},
success: function(res){
atentionare(res); // this is a function that displays a message on the screen
load_signin_options(); // this is a function that appends more buttons on my navbar
}
})
});
and my server code:
app.post('/conectare', function(req,res ){
var user = req.body.username;
var pass = req.body.password;
MongoClient.connect(uri, function(err,db){
var dbc=db.db("mydb");
dbc.collection('user').find({username: {$eq: user}}).toArray(function (err, result){
let len= result.length;
if( len == 0 ){
res.send("User does not exist");
}
else{
var a = result[0];
if(pass===a.password){
res.send("successfully connected");
req.session.username = user;
console.log("parola e buna");
}
else{
res.send("Incorrect password");
}
}
});
db.close();
});
});
this is my session, i also installed express-session
app.use(session({
secret: 'secret',
resave: true,
cookie: { maxAge: 0 },
saveUninitialized: true
}));
i tryed to follow this post How to create sessions in node.js
but and i found out that my session doesnt work, but i don;t understand how to make it work
You set your cookie to maxAge = 0, meaning you're never creating the cookie needed to hold the sessionId.
Change to:
app.use(session({
secret: 'secret',
resave: true,
cookie: { maxAge: 3600 },// one hour
saveUninitialized: true
}));

Node/Express req.session.user "undefined"

I am a beginner Node.js developer and am working on a web app for which I need session management. I'm defining Express session like the following:
app.use(cookieParser());
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: true,
cookie: {
expires: 600000
}
}));
And set the session variable in /signup (not shown) and /login. However, if I try to access req.session in any other route, it shows up as "undefined". Does anyone have any input on this?
router.post('/login', async function(req, res) {
console.log(req.body);
var email = req.body.email,
password = req.body.password;
let user = await User.findOne({ email: email });
if (!user) {
res.status(400).send("Failure");
} else if (!bcrypt.compareSync(req.body.password, user.password)) {
res.status(400).send("Failure");
} else {
req.session.user = user;
res.status(201).send("Success");
}
});

Creating session within monk's findOne command

This simple bit of code illustrates the problem: The second session does not save. How can I make this work?
router.post('/users/login', function (req, res) {
var db = req.usersDb;
var users = db.get('users');
req.session.test = "This works";
req.session.save();
users.findOne({ username: req.body.username}).on('success', function (doc) {
console.log(doc.email); //this works
req.session.email = doc.email; //This not working
req.session.save();
});
});
Changing the express-session 'resave' property in the options object to false solved the problem.
example:
app.use(session({ genid: function(req) { return guid() }, secret: 'secret', resave: false, saveUninitialized: true }))

Resources