Printing a session object in ExpressJS - node.js

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}}));

Related

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');
});
})

how to access express-myconnection db connection from app.js to model node js

I have defined express-myconnection database connection in app.js now i want to use that database connection in models like tasks.js how do I implement that connection in models also.Please suggest me better option.
app.js
var createError = require('http-errors');
var express = require('express');
var session = require('express-session');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
// var passport = require('passport');
var cors=require('cors');
var flash = require('connect-flash');
var mysql = require('mysql');
// require('./config/passport')(passport);
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var Tasks=require('./routes/Tasks');
var app = express();
var customers = require('./routes/customers');
var login = require('./routes/login');
var connection = require('express-myconnection');
// view engine setup
// app.set('port', process.env.PORT || 4300);
app.engine('pug', require('pug').__express);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// app.use(passport.initialize());
app.use(session({
secret: 'justasecret',
resave:true,
cookie: {
httpOnly: true,
maxAge : 10000,
},
saveUninitialized: true
}));
/*------------------------------------------
connection peer, register as middleware
type koneksi : single,pool and request
-------------------------------------------*/
// app.use(
// connection(mysql,{
// host: 'localhost',
// user: 'root',
// password : '',
// port : 3306, //port mysql
// database:'nodejs'
// },'pool')
// );//route index, hello world
dbOptions = {
host: 'localhost',
user: 'root',
password: '',
port: 3307,
database: 'nodejs'
};
// const db = mysql.createPool(dbOptions);
app.use(connection(mysql, dbOptions, 'pool'));
app.use(cors());
app.use(logger('dev'));
// app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(flash());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/customers', customers);
app.use('/admin',login);
app.use('/tasks',Tasks);
// require('./routes/login.js')(app, passport);
// 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;
inside models/tasks.js=>
var Task={
getAllTasks:function(callback){
return db.query("Select * from task",callback);
},
getTaskById:function(id,callback){
return db.query("select * from task where Id=?",[id],callback);
},
addTask:function(Task,callback){
return db.query("Insert into task values(?,?,?)",[Task.Id,Task.Title,Task.Status],callback);
},
deleteTask:function(id,callback){
return db.query("delete from task where Id=?",[id],callback);
},
updateTask:function(id,Task,callback){
return db.query("update task set Title=?,Status=? where Id=?",[Task.Title,Task.Status,id],callback);
}
};
module.exports=Task;
express-myconnection extends request object with getConection(callback) function, this way connection instance can be accessed anywhere in routers during request/response life cycle:
// myroute.js
...
module.exports = function(req, res, next) {
...
req.getConnection(function(err, connection) {
if (err) return next(err);
connection.query('SELECT 1 AS RESULT', [], function(err, results) {
if (err) return next(err);
results[0].RESULT;
// -> 1
res.send(200);
});
});
...
}
...

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

connect-redis and express-session results in req.session undefined

I'm trying to get express-session to store the session in Redis, but it doesn't seem like it wants to save. When I revert back to default session store it works flawlessly. The Redis daemon is hosted on a Vagrant VM with default configuration, and the app is able to connect to it, although it doesn't want to save sessions to it.
Here's my code:
var express = require('express');
var glob = require('glob');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var compress = require('compression');
var methodOverride = require('method-override');
var session = require('express-session');
var passport = require('passport');
var redis = require('redis');
var RedisStore = require('connect-redis')(session);
var auth = require('./passport');
var flash = require('connect-flash');
module.exports = function(app, config) {
app.set('views', config.root + '/app/views');
app.set('view engine', 'jade');
// app.use(favicon(config.root + '/public/img/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(session({
store: new RedisStore({
host: config.redis.host,
port: config.redis.port
}),
secret: config.secret,
saveUninitialized: true,
resave: false
}));
/*app.use(session({
secret: config.secret,
saveUninitialized: true,
resave: true
}));*/
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(compress());
app.use(express.static(config.root + '/public'));
app.use(methodOverride());
var controllers = glob.sync(config.root + '/app/controllers/*.js');
controllers.forEach(function (controller) {
require(controller)(app);
});
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
if(app.get('env') === 'development'){
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err,
title: 'error'
});
});
}
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {},
title: 'error'
});
});
};
As you can see, I got the default one commented out, and if I remove those comments and comment out the redis store, it works as it should. Any clues why this is happening? I'm not getting a single error.
You probably have some connection errors, but connect-redis does not output them to console (see connect-redis source code). To see them you can create a separate module that creates a client instance and pass it to RedisStore constructor:
// redisClient.js
var redis = require('redis');
var redisClient = redis.createClient('localhost', 6379); // replace with your config
redisClient.on('error', function(err) {
console.log('Redis error: ' + err);
});
module.exports = redisClient;
Redis client emits also other event that may be helpful in debugging - see node-redis docs
// your code
var redisClient = require('./redisClient.js`);
(...)
app.use(session({
store: new RedisStore({
client: redisClient
}),
secret: config.secret,
saveUninitialized: true,
resave: false
}));

Resources