ReferenceError: session is not defined with ('connect-mongo')(session), - node.js

I'm trying to add connect-mongo in order to save sessions when nodeJS restarts.
Per the documentation I added:
MongoStore = require('connect-mongo')(session),
and in my require('express-session') I added
store: new MongoStore({
url: mongooseDB,
touchAfter: 24 * 3600
})
and commented out app.use(passport.session());
I'm getting an error: ReferenceError: session is not defined which is pointed to MongoStore = require('connect-mongo')(session),
I've added my app.js file for reference. How can I fix this?
'use strict';
const express = require('express'),
app = express(),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
MongoStore = require('connect-mongo')(session),
passport = require('passport'),
flash = require('connect-flash'),
LocalStrategy = require('passport-local'),
methodOverride = require('method-override'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
User = require('./models/user'),
faker = require('faker'),
path = require('path');
const indexRoute = require('./routes/index'),
usersRoute = require('./routes/users'),
giftsRoute = require('./routes/gifts.js'),
searchRoute = require('./routes/search');
const mongooseDB = 'mongodb://localhost/giftcashing';
mongoose.connect(mongooseDB);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.use(methodOverride("_method"));
app.use(flash());
app.use(require('express-session')({
secret: 'anything',
resave: false,
saveUninitialized: false,
store: new MongoStore({
url: mongooseDB,
touchAfter: 24 * 3600
})
}));
// PASSPORT CONFIGURATION
app.use(passport.initialize());
// app.use(passport.session());
// use static authenticate method of model in LocalStrategy
passport.use(new LocalStrategy(User.authenticate()));
// use static serialize and deserialize of model for passport session support
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(function (req, res, next) {
res.locals.currentUser = req.user;
res.locals.error = req.flash('error');
res.locals.success = req.flash('success');
next();
});
// catch 404 and forward to error handler
// app.use(function(req, res, next) {
// var err = new Error('Not Found');
// err.status = 404;
// next(err);
// });
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.use('/', indexRoute);
app.use('/users', usersRoute);
app.use('/gifts', giftsRoute);
app.use('/search', searchRoute);
module.exports = app;

The variable session is not initialized when you are calling
MongoStore = require('connect-mongo')(session).
Add session = require('express-session') before initializing MongoStore.

Related

"express-session deprecated undefined resave option; provide resave option node_modules/admin-bro-expressjs/plugin.js:138:14"

am using admin-bro for my admin , it works fine until i try to use its authentication, when i try to login to the admin using the admin-bro login form dashboard ,it just keeps loading with no response,my terminal says
express-session deprecated undefined resave option; provide resave option node_modules/admin-bro-expressjs/plugin.js:138:14
express-session deprecated undefined saveUninitialized option; provide saveUninitialized option node_modules/admin-bro-expressjs/plugin.js :138:14 AdminBro: bundle ready we're connected!
here's my app.js file
require('dotenv').config();
const express = require('express');
const engine = require('ejs-mate');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const passport = require('passport');
const User = require('./models/user');
//const formidableMiddleware = require('express-formidable');
const session = require('express-session');
const mongoose = require('mongoose');
const methodOverride = require('method-override');
// const seedPosts = require('./seeds');
// seedPosts();
// require routes
const index = require('./routes/index');
const posts = require('./routes/posts');
const reviews = require('./routes/reviews');
const adminRouter= require('./routes/admin.router');
const app = express();
//connect to database
//var url = process.env.DATABASEURL || "mongodb://localhost:27017/surf-shop"
mongoose.connect("mongodb://localhost:27017/surf-shop" , {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('we\'re connected!');
});
// use ejs-locals for all ejs templates:
app.engine('ejs', engine);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// set public assets directory
app.use(express.static('public'));
//app.use(favicon(path.join(__dirname, 'public', 'favi.jpg')));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(methodOverride('_method'));
// Configure Passport and Sessions
app.use(session({
secret: 'hang ten dude!',
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
// set local variables middleware
app.use(function(req, res, next) {
// req.user = {
// // '_id' : '5bb27cd1f986d278582aa58c',
// // '_id' : '5bc521c0b142b6d7f7523406',
// '_id' : '5bfed10ad176f845e38aec92',
// 'username' : 'ian3'
// }
res.locals.currentUser = req.user;
// set default page title
res.locals.title = 'Surf Shop';
// set success flash message
res.locals.success = req.session.success || '';
delete req.session.success;
// set error flash message
res.locals.error = req.session.error || '';
delete req.session.error;
// continue on to next function in middleware chain
next();
});
// Mount routes
app.use('/', index);
app.use('/posts', posts);
app.use('/posts/:id/reviews', reviews);
app.use('/admin', adminRouter);
//app.use(formidableMiddleware());
// catch 404 and forward to error handler
app.use(function(req, res, next) {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// // set locals, only providing error in development
// res.locals.message = err.message;
// res.locals.error = req.app.get('env') === 'development' ? err : {};
// // render the error page
// res.status(err.status || 500);
// res.render('error');
console.log(err);
req.session.error = err.message;
res.redirect('back');
});
module.exports = app;
here's my admin.route.js file
const AdminBro = require('admin-bro');
const AdminBroExpress = require('admin-bro-expressjs');
const AdminBroMongoose = require('admin-bro-mongoose');
const mongoose = require('mongoose');
AdminBro.registerAdapter(AdminBroMongoose);
const adminBro = new AdminBro({
databases: [mongoose],
rootPath: '/admin',
});
const ADMIN = {
email: process.env.ADMIN_EMAIL || 'admin#example.com',
password: process.env.ADMIN_PASSWORD || 'lovejs',
}
const router = AdminBroExpress.buildAuthenticatedRouter(adminBro, {
cookieName: process.env.ADMIN_COOKIE_NAME || 'admin-bro',
cookiePassword: process.env.ADMIN_COOKIE_PASS || 'some-super-sensitive-password',
authenticate: async (email, password) => {
if (ADMIN.password === password && ADMIN.email === email) {
return ADMIN
}
return null
}
});
module.exports = router;
any help would be appreciated
Put your app.use('/admin', adminRouter); before app.use(express.json());
That was how I solved the problem because admin bro has an issue with express body parser or the built in one.
delete app.use(express.urlencoded({ extended: true }));

Passport req.user is undefined when using GitHub strategy

I'm trying to set up Github authentication using passport.
app.js (where i set up middleware)
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const session = require('express-session');
const passport = require('passport');
const GitHubStrategy = require('passport-github').Strategy;
var indexRouter = require('./routes/index');
var app = express();
const helmet = require('helmet');
app.use(helmet());
const passportConfig = require('./config');
//================================PASSPORT CONFIG=======================
app.use(session({
secret: 'test1234',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new GitHubStrategy(passportConfig,
function (accessToken, refreshToken, profile, cb) {
return cb(null, profile)
}
));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
done(null, user);
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
As you can see, I set up express session and use passport.initialize() and passport.session()
But when i try retrieving the req.user object in any of my routes, it returns undefined. Does anyone know what the reason for this might be?
I think this is an issue of app.use(passport.session()); middleware, Manually saving the session before doing any action.
app.get('slack/callback', function(req,res){
passport.authorize('slack');
//Manually save session before redirect.
req.session.save(function(){
res.redirect('/someURL');
});
})

Printing a session object in ExpressJS

I am trying to print out a session object in middleware of an ExpressJS framework. I am new to a session with express and want to see if the object saves to Redis which I have configurated in the app.js file
[index.js (router)]
router.use('/', function(req, res, next) {
req.session.user = {};
req.session.user.browserInformation = req.headers['user-agent'];
console.log(req.session);
next();
});
router.get('/', function(req, res, next) {
res.render('index.html');
});
[The app.js File:]
'use strict';
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const bodyParser = require('body-parser');
const session = require('express-session');
const redis = require('redis');
const redisStore = require('connect-redis')(session);
const client = redis.createClient();
const app = express();
const _Utils = require('./application/_Utils');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(bodyParser.urlencoded({
extended: false
}))
app.use(bodyParser.json())
app.use(express.static(path.join(__dirname, 'views')));
//require('./config/router')(app);
let indexRouter = require('./routes/index');
app.engine('html', require('ejs').renderFile)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.use(session({
secret: _Utils.getHashedValue(),
store: new redisStore({
host: '127.0.0.1',
port: 6379,
client: client,
ttl: 3600000
}),
saveUninitialized: false,
resave: false,
cookie: {
expires: new Date(Date.now() + 3600000),
maxAge: 3600000
},
}));
module.exports = app;
An issue I am having is that nothing is printing or Redis is empty when I execute KEYES * command in the terminal client interface
EDIT: Added a whole app.js file
in my case code is worked:
console.log(req.session);
Also use this in attend some information to session use this:
req.session.mail="a#b.com";
İf you are in localhost add this unsecure cookie options in our code. For example:
app.use(session({ secret: 'GttiginYagmurlagelkuskunumyagmuralara' ,resave: true,
saveUninitialized: true,
cookie: { secure: false,maxAge: 3600000}}));

Express post do not post data leaving req.body undefined

I was trying to write some test which will emulate the post, but I have realised that nothing is posting. After further debugging, I realised that req.body is always undefined. Question is where did I make a mistake and how do I fix it. I seems that the problem is somewhere in the app.js file with order how the middleware loads but I can not figure it out where.
app.js
'use strict';
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const bodyParser = require('body-parser');
const fs = require('fs');
const session = require('express-session');
const redis = require('redis');
const mongoose = require('mongoose');
const redisStore = require('connect-redis')(session);
const client = redis.createClient();
const app = express();
const _UTILS = require('./application/_UTILS');
const db = JSON.parse(fs.readFileSync('/srv/webkb_mean/config/configFiles/database.json', 'utf8'));
mongoose.connect('mongodb://' + db['mongodb']['url'] + '/webKB-main');
mongoose.Promise = global.Promise;
app.use(session({
secret: _UTILS.getHashedValue(),
// create new redis store.
store: new redisStore({
host: 'localhost',
port: 6379,
client: client,
ttl: 36000
}),
saveUninitialized: false,
resave: false
}));
require('./config/router')(app);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(bodyParser.json())
app.use(express.static(path.join(__dirname, 'views')));
app.engine('html', require('ejs').renderFile)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
// app.use(function(err, req, res, next) {
// // set locals, only providing error in development
// res.locals.message = err.message;
// res.locals.error = req.app.get('env') === 'development' ? err : {};
//
// // render the error page
// res.status(err.status || 500);
// res.render('error');
// });
//
module.exports = app;
Your adding your bodyParser middleware to your server after you’ve added your routes. This is because express executes middleware(which includes routers since they are also middleware) in the order which they were added via .use().
Just move your router registration line:
require('./config/router')(app);
After your last middleware and before your 404 NOT FOUND handler.
app.engine('html', require('ejs').renderFile)
require('./config/router')(app);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});

http-proxy-middleware not proxying requests if placed after cookieparser

The middleware works properly if placed before the cookie parser.But
the session becomes undefined.
If i move the proxy middleware after the cookie parser it does not
proxy requests silently fails without any errors.I tried creating a post request but nothing happens.
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 cors = require('cors');
var redis = require('redis');
var redisClient = redis.createClient();
var RedisStore = require('connect-redis')(session);
var proxy = require('http-proxy-middleware');
var config = require('config');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
var sessionMiddleware = session({
store: new RedisStore({
client:redisClient
}),
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(sessionMiddleware);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//cookie parser
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.use(cors());
//proxy middleware
app.use('/api', proxy({
target: 'http://localhost:4000',
changeOrigin: true,
onProxyReq: function (proxyReq, req, res) {
proxyReq.setHeader('USER_ID', req.session.user_id);
proxyReq.setHeader('TOKEN',config.get('token'));
}
}));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
http-proxy-middleware npm module middleware
app.use('/api', proxy({
target: 'http://localhost:4000',
changeOrigin: true,
onProxyReq: function (proxyReq, req, res) {
proxyReq.setHeader('USER_ID', req.session.user_id);
proxyReq.setHeader('TOKEN',config.get('token'));
}
}));
If you are keeping any parser middlewares, It will format your request, which is not expected by http-proxy-middleware.
We should place proxy middleware before parser middleware or you can try it out.
onProxyReq: function (proxyReq, req, res) {
if (req.body) {
const body = JSON.stringify(req.body)
proxyReq.setHeader('Content-Type', 'application/json')
proxyReq.setHeader('content-length', body.length)
delete req.body
proxyReq.write(body)
proxyReq.end()
}
},
Note: Changes has to be done with respect to content type

Resources