I'm having problem with express-session, it seems like it's not saving my user session. Here is when I declare my session:
// Session
// app.use(express.urlencoded({ extended: true }));
app.use(session({
secret: "key per i cookie",
saveUninitialized: false,
resave: false,
store: MongoStore.create({
mongoUrl: process.env.URI,
autoRemove: 'disabled'
}),
cookie: { maxAge:30000, secure:false }
}));
app.use(cookieParser());
app.use(function(req, res, next) {
res.locals.session = req.session.user;
next();
});
And then saving it when user is logged in
app.post('/login', async (req,res) => {
const { username, password } = req.body
const user = await User.findOne({username}).lean()
if(!user) {
return res.json({status:'error', error:'Username o password non validi'})
}
if (await bcrypt.compare(password, user.password)) {
const token = jwt.sign({
id: user._id,
username: user.username
}, JWT_SECRET);
req.session.user = username;
req.session.save();
console.log('Utente loggato ' + req.session.user);
return res.json({ status: 'ok', data: token });
}
res.json({status:'error',error:'Username o password non validi'});
});
Apparently in the post I save the session but after login, when trying to access in an EJS page with
<% if(session.user) { %>
<h1>Session stored</h1>
<% } else { %>
<p>No session</p>
<% }%>
I got no session stored. What am I doing wrong?? Thanks in advance
I think you should use the secret phrase used in your session in your cookie parser
app.use(cookieParser("key per i cookie"))
Related
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
}));
Can I please get some help, I have been searching all over the internet for this and I cannot seem to find the answer that I am looking for.
So I would love to implement expression-session and mongoDB as the store, so session creation I managed to get that done and also saving the session within the store i.e MongoDB managed to get that done.
The problem now comes to when I have to send the session cookie to the client, so I have my server(NodeJS) running on port 5000 and I have the client(ReactJS) running on port 3000, so now how can I send that cookie to the client and flag it as httpOnly cookie?
This is how I tried to setup express-session
mongoose
.connect(MongoURI, {
useNewUrlParser: true,
useCreateIndex: true
})
.then(() => console.log("MongoDB connected..."))
.catch((err) => console.log(err));
const mongoDBstore = new MongoDBStore({
uri: MongoURI,
collection: "mySessions"
});
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(
session({
name: COOKIE_NAME,
secret: 'SESS_SECRET',
resave: true,
saveUninitialized: false,
store: mongoDBstore,
cookie: {
maxAge: 1000 * 60 * 60 * 3,
sameSite: false,
secure: false
}
})
);
This is where I wanted to send the cookie once user logs in
router.post("/login", (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ msg: "Please enter all fields" });
}
User.findOne({ email }).then((user) => {
if (!user) return res.status(400).json({ msg: "User does not exist" });
bcrypt.compare(password, user.password).then((isMatch) => {
if (!isMatch) return res.status(400).json({ msg: "Invalid credentials" });
const sessUser = { id: user.id, name: user.name, email: user.email };
req.session.user = sessUser;
res.json({ msg: " Logged In Successfully", sessUser });
});
});
});
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");
}
});
I'm encountering a little problem when using passport.js with express 4.11.1
Below is my app.js
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
function(username, password, done) {
if(username == '1' && password == '1') {
var user = {username: 'test',id: 123,firstName: 'test'};
return done(null, user);
} else {
return done(null, false, {message: 'Incorrect username or password'});
}
}
));
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(username, done) {
var user = {
username: 'test',
id: 123,
firstName: 'test'
};
done(null, user);
});
module.exports = passport;
Then I modified my app.js, adding the middleware
var passport = require('./auth');
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true,
cookie: { secure: true }
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use(passport.session());
At last, I defined in the router:
var passport = require('../auth');
router.get('/login', function (req, res, next) {
res.render('login', {title: 'Login', message: ''});
});
router.post('/login',
passport.authenticate('local',
{
successRedirect: '/user2',
failureRedirect: '/login'
}));
router.get('/user2', function(req, res) {
console.log(req.session.passport);
if(req.session.passport.user === undefined) {
res.redirect('/login');
} else {
res.render('user2', {title: 'Welcome!', user: req.user});
}
});
Now the problem that I found is that I can successfully login, however when I try to print out req.session.passport, I found the passport object in session is {}. I guess maybe it's because the passport.serializeUser function doesn't really work, but when I try printing out the user object passed to the passport.serializeUser function, it has values. Can someone help me look into this issue? Thanks in advance.
Your code looks fine, except this part:
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true,
cookie: { secure: true } <<<<<<<<<<
}));
docs say that you should use secure cookies when you are using https, so excluding this field should fix your problem.
secure boolean marks the cookie to be used with HTTPS only.
I'm trying to use a session ID from my mongo database as the sessionID within express-session and have these details stored within a connect-redis session store.
I keep getting 'TypeError: cookie required'
This appears to be a bug, but could somebody check my logic here please:
I've stripped the code down to it's bare bones and removed anything that's not required to create the issue.
'use strict';
var express = require('express'),
session = require('express-session'),
redisStore = require('connect-redis')(session),
bodyParser = require('body-parser'),
app = express();
app.use(session({
name: 'test',
genid: function(req) {
if (typeof req.sessionID != 'undefined') return req.sessionID;
},
cookie: {
httpOnly: false,
path: '/',
maxAge: null
},
resave: false,
saveUninitialized: false,
secret: 'finbarboobar',
store: new redisStore({
host: 'localhost',
port: 6379,
prefix: 'kTest:'
})
}));
app.use(bodyParser.urlencoded({ extended: false }));
//router
app.route(['/'])
.get(function(req, res) {
if (req.session.email) return res.redirect('/admin');
res.send('<h1>Login</h1><form action="/login" method="POST" accept-charset="UTF-8" ><input placeholder="Enter Email" name="email" type="email" autofocus="autofocus"><input type="submit" value="sign in"></form>');
});
app.route(['/login'])
.post(function(req, res) {
req.sessionID = 1;
req.session.regenerate(function(error) {
if (error) {
console.log(error);
} else {
req.session.email = req.body.email;
res.redirect('/admin');
}
});
});
app.get('/admin', function(req, res) {
if (req.session.email) {
res.send('<h1>Hello ' + req.session.email + '</h1>logout');
} else {
res.redirect('/');
}
});
app.get('/logout', function(req, res) {
req.session.destroy(function(error) {
if (error) {
console.log(error);
} else {
res.redirect('/');
}
})
});
app.listen(3001);
Thanks for looking at this.
The issue here was a bug within express-session package which has been addressed on github
The problem was that the req.sessionID needs to be be a string. So in the case of the example above, I was sending a number and in my original code I was sending a mongoDB._id object.
The solution to the above would be to use:
req.sessionID = "1";
The solution to the real issue would have been to use:
req.sessionID = mongoDBSession._id.toString();
I hope this helps someone else with these issues at some point.