Can't store session in MongoDB with passport - node.js

I'm new to Node JS and I'm trying to store session in mongoDB by using the connect-mongo npm package , once I add the following line - i get an error :
app.use(session({
saveUninitialized: true,
resave: true,
store : new MongoStore({ // adding this will cause an error
db: 'users'
})
}));
Here are the session parts of my code (i'm using express 4.16) :
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var expressValidator = require('express-validator');
var multer = require('multer');
var upload = multer({dest: './uploads'});
var flash = require('connect-flash');
var bcrypt = require('bcryptjs');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var MongoStore = require('connect-mongo')(session);
var db = mongoose.connection;
session(app, mongo.initSessionStore);
app.use(session({
saveUninitialized: true,
resave: true,
store : new MongoStore({
db: 'users'
})
}));
// Passport
app.use(passport.initialize());
app.use(passport.session());

You haven't sent instance of MonogDB to MongoStore. You sent string 'user', and it expect database instance. So it can't connect to MonogDB.
If you are using Mongoose you need first to connect to database, and then you can usemongoose.connection for MongoStore:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
app.use(session({
saveUninitialized: true,
resave: true,
store : new MongoStore({
mongooseConnection: db
})
}));

Related

module priority cannot solve my 'passport.initialize() middleware not in use'

var express = require('express');
var app = express();
var session = require('express-session');
var MySQLStore = require('express-mysql-session')(session);
var cookieParser = require('cookie-parser');
var bkfd2Password = require('pbkdf2-password');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var hasher = bkfd2Password();
var conn = require('../db/db_con')();
var config = require('../db/db_selector');
app.use(cookieParser());
app.use(express.urlencoded({ extended: false }));
app.use(passport.initialize());
app.use(passport.session());
app.use(session({
secret: '432984252#!%#!$',
resave: false,
saveUninitialized: true,
store: new MySQLStore(config.dbConfig, conn)
}));
var router = express.Router();
:: this is head of 'login.js',
Node, express, passport, session, mysql...
For solving middle-ware hell,
I took the solutions by stackoverflow, about 100~200 questions and answers, but failed.
And when I executed login process, the error is from routes/signup.js:70:25,
the part is,
console.log('LocalStrategy', account);
done(null, account);
I can show localstrategy and account,
and done() func makes hell.
signup.js is similar to login.js.

Multiple users assigned to the same session ID (express-session)?

I am using express session and MongoStore for storing session ID
Here is my app.js
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var passport = require('passport');
var flash = require('connect-flash');
var path = require('path');
var app = express();
var user = require('./models/userModel');
//------Connect to database
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/porto', { useMongoClient: true });
//------Config Passport
require('./config/passport.js')(passport);
//------Adding middlewares
app.use(bodyParser.urlencoded({extended:true}));
app.use(cookieParser());
app.use(session({
secret : 'secret',
saveUninitialized : true,
resave : true,
store : new MongoStore({mongooseConnection : mongoose.connection})
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
My route handler for posting a ToDo
app.post('/addTodo',function(req,res){
console.log(req.body);
console.log(req.user._id); // Here the user id is changed
console.log(req.sessionID); // Here the sessionID never changed, but assigned to the newly logged in user
var todo = req.body.todo;
userModel.update(
{ _id: req.user._id },
{ $push: { todos: todo } },
function(err,done){
if (err)
return err;
return done;
}
);
res.redirect('/profile');
});

Why can't I get the value of the session?

this is my code of app.js, and I save session in mongoDB.
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const session = require('express-session');
const mongoStore = require('connect-mongo')(session);
const db = mongoose.connect("mongodb://localhost/course");
app.use(cookieParser());
app.use(cookieSession({ //session
secret: "system",
store: new mongoStore({
mongooseConnection: db.connection,
collection: "sessions"
})
}))
when I want to get req.session.user, I get undefined.
but I save session when user login.
exports.fetchCourse = async (req, res) => {
console.log("session is: " + req.session.user);
if(req.session.user) {
const user = await User.findOne({_id: req.session.user._id}).populate("course");
console.log("course are: " + user.course.length);
res.status(200).send({
code: 1,
data: user.course,
msg: "获取全部课程"
})
}
}
You are using cookieSession instead of expressSsession.
according to the docs your code shall look similar to this (if you use express 4 and above):
const session = require('express-session');
const mongoStore = require('connect-mongo')(session);
const db = mongoose.connect("mongodb://localhost/course");
app.use(session({
secret: "system",
store: new mongoStore({
mongooseConnection: db.connection,
collection: "sessions"
})

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.

Redis with express and passport

I am trying to using Redis with my exsiting application
Here is my app.js code
var express = require('express'),
request = require('request'),
http = require('http'),
path = require('path');
var app = express();
var routes = require('./routes');
var passport = require('passport');
var flash = require('connect-flash');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var busboy = require('connect-busboy');
var policies = require('./policies/admin');
var config = require('./config');
require('./libs/passport')(passport);
app.configure(function () {
app.use(express.session({ secret: 'secertkey', cookie: { maxAge : 2592000000 } })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
});
Which is working fine.
I want to use Rediss along with passport,
Is this possible and how can i do
Thanks
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'
}));
for reference
https://www.npmjs.com/package/connect-redis

Resources