I am trying to reuse the database object.The session intialization is working fine outside the Mongoconnect callback. But when I move it inside the call back , the session cookie is not being set in the browser . Any ideas??
var express=require('express');
var bodyParser=require('body-parser');
var cookieParser=require('cookie-parser');
var session=require('express-session');
var mongodb=require('mongodb'),
MongoClient = mongodb.MongoClient;
var MongoStore = require('connect-mongo')(session);
var util=require('util');
var assert=require('assert');
var db;
var app=express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(cookieParser());
MongoClient.connect('mongodb://localhost:27017/mydb',function(err,database){
if(!err)
{
app.use(session(
{ name:'sessionCookie',secret:'secret',saveUninitialized:true,resave:true ,
store: new MongoStore({ db:database })
}
));
app.listen(3000);
}
});
This seems to be a timing issue between the time the app object is intialized aand the session is intilaized. I chnaged the code a bit and the issue seems to be fixed. I am not entirely sure about the root cause. Feel free to chip in
var express=require('express');
var bodyParser=require('body-parser');
var cookieParser=require('cookie-parser');
var session=require('express-session');
var mongodb=require('mongodb'),
MongoClient = mongodb.MongoClient;
var MongoStore = require('connect-mongo')(session);
var util=require('util');
var assert=require('assert');
var db;
var app;
MongoClient.connect('mongodb://localhost:27017/mydb',function(err,database){
if(!err)
{
app=express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(cookieParser());
app.use(session(
{ name:'sessionCookie',secret:'secret',saveUninitialized:true,resave:true ,
store: new MongoStore({ db:database })
}
));
app.listen(3000);
}
});
Related
I am working on making adjustments to teammates code and I haven't been able to understand how they have done their routing. I am attempting to have Express run a middleware script when an end-user goes to a new session of the web application.
I don't know what to test next to figure out how they have done their routing.
Main.js
// Dependencies
var http = require('http');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var busboy = require('connect-busboy');
var cors = require('cors');
var mongoose = require('mongoose');
// Configuration
var config = require('./config');
var twilio = require('twilio');
// Database
mongoose.connect(config.database);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function(){
console.log('Connected to database');
});
var app = express();
app.set('port', process.env.PORT || 3000);
// Setup middleware
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser(config.sessionSecret));
app.use(express.static(path.join(__dirname, 'dist')));
app.use(busboy());
app.use(cors({
origin: true,
credentials: true
}));
app.all('/*',function(req,res){
twilio.notifyOnSession();
console.log('Message Sent');
})
var server = http.createServer(app);
var port = app.get('port');
server.listen(port);
console.log('Listening on port ' + port);
// Load server router
require('./router')(app);
/router/index.js
var path = require('path');
module.exports = function(app){
console.log('Initializing server routing');
require('./auth')(app);
require('./api')(app);
// Determine if incoming request is a static asset
var isStaticReq = function(req){
return ['/auth', '/api', '/js', '/css'].some(function(whitelist){
return req.url.substr(0, whitelist.length) === whitelist;
});
};
// Single page app routing
app.use(function(req, res, next){
if (isStaticReq(req)){
return next();
}
res.sendFile(path.join(__dirname, '../dist/index.html'));
});
};
Your app.all('/*' is swallowing all requests before they can hit your router.
Don't do that.
I was able to resolve the issue by creating a new route with twilio.js and having the router look for the url twilio/new. Thanks all for the help.
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');
});
I am implementing a simple login functionality and storing the data in the express-session but not able to get it back.
In loginDb.js file in login function i am storing the userId in session variable and in getLoginStatus function i am trying to access the userId but it is returing as undefined.
I have gone through many post related to similar issue but nothing helped in my case. Don't know what i am doing wrong here. Below is the code.
server.js
var express = require('express');
var pg = require('pg');
var cookieParser = require('cookie-parser');
var bodyparser = require('body-parser');
var session = require('express-session');
var path = require('path');
const port = 3000;
const loginroute = require('./Routes/login');
var app=express();
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: 'This is a secret',
resave: true,
saveUninitialized:true,
cookie: {
secure: false,
maxAge: 60000
}
}));
//Routes
app.use('/api/loginroute',loginroute);
app.listen(port,function(){
console.log('app listening to port:'+port);
});
login.js
const express = require('express');
const router = express.Router();
const db = require('../DataAccessLayer/loginDb');
router.get('/getLoginStatus', db.getLoginStatus);
router.post('/login', db.login);
module.exports = router;
loginDb.js
var config = require('../Config/config');
var session = require('express-session');
var pg = require('pg');
var pool = new pg.Pool(config.development.db);
function getLoginStatus(req, res, next){
var userId = req.session.userId;
};
function login(req, res, next) {
pool.connect(function(err, client, done) {
if (err) {
console.log("not able to get connection "+ err);
res.status(400).send(err);
}
var q = "select id from nodetest.users where name=$1 and password=$2";
client.query(q, [req.body.username, req.body.password], function(err, result) {
done();
if(err) {
return console.error('error running query', err);
}
if(result.rowCount>0){
req.session.userId = result.rows[0].id;
}
res.send(result.rows);
});
});
};
module.exports = {
login:login,
getLoginStatus:getLoginStatus
};
Set cookieParser secret key similar as that of express-session secret key will fix the issue.
app.use(cookieParser('This is a secret'))
Doc Says
Using cookie-parser may result in issues if the secret is not the same
between this module and cookie-parser.
I have this initialisation code;
app.use(cookieParser);
var redis = require('redis');
var redisOptions = {}
redisOptions.client = redis.createClient(<removed>, 'pub-redis-12124.us-east-1-2.3.ec2.garantiadata.com');
app.use(session({
store: new RedisStore(redisOptions),
secret: 'keyboard cat',
resave: true,
saveUninitialized: true
}));
In my routing, I have this;
router.post('/login', function (req, res) {
var users = req.db.get('users');
users.findOne({email: req.body.email}, function (err, user) {
console.log(user);
if (req.body.password == user.password) {
req.session.id = user._id;
console.log("id:" );
res.send('successful login' + req.session.id);
} else {
// Make sure to log failed auth requests
var log = req.db.get('failed_auth');
var fail_info = {};
fail_info.email = req.body.email;
fail_info.ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
fail_info.timestamp = Date.now();
log.insert(fail_info, function(doc) {
res.send('bad creds');
});
}
});
});
However when I try to go through this code, I get this error;
TypeError: Cannot set property 'id' of undefined
My Redis server is one of the free hosted ones from redislabs. I'm not sure if I need to authenticate although I don't think that I do. Any tips on the way forward?
edit:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var bodyParser = require('body-parser')
var cookieParser = require('cookie-parser')();
var session=require('express-session');
var RedisStore = require('connect-redis')(session);
// New Code
var monk = require('monk');
var db = monk('localhost:27017/manpoints');
var routes = require('./routes/index');
var account = require('./routes/account')
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
Ignore the mess/unused stuff, I've been trying lots of different things trying to get this to work.
I try to configure my connect-mongo in the way I can use session in nodejs that is persisted with mongo. I use following code
var mongoose = require('mongoose');
function connect(url, callback) {
mongoose.connect(url);
var connection = mongoose.connection;
connection.on('error', console.error.bind(console, 'connection error:'));
connection.once('open', function() {
console.log("Mongoose connected at: ", url);
callback(connection);
});
}
var express = require("express");
var body_parser = require('body-parser');
var cookie_parser = require('cookie-parser');
var hogan_express = require('hogan-express');
var session = require('express-session');
var mongo_store = require('connect-mongo')(session);
var express = require("express");
var app = express();
app.engine('html', hogan_express);
app.set('view engine', 'html');
app.set("views", "views");
app.use("/libs", express.static("bower_components"));
if (!config.development) {
app.use(express.static("min"));
}
app.use(express.static("public"));
connect("MONGODBURL",function(mongoose_connection){
app.use(body_parser.json());
app.use(cookie_parser());
app.use(session({
secret: "asd",
store: new mongo_store({
mongoose_connection: mongoose_connection
// db: mongoose_connection.db
})
}));
})
I have tried everything but executing some code I have never the object session in my res refrence.
Getting: TypeError: Cannot set property 'asd' of undefined
Code:
app.get("/rest/test",function(req, res) {
req.session.asd="test";
res.send(req.session.asd)
});
Somone could give a hint for a solution?
You need to define your routes after your configure your session.
...
app.use(session....
...
app.get("/...
Inside your connect's callback in your case. Probably start listening inside it only as well.
connect("MONGODBURL",function(mongoose_connection){
app.use(body_parser.json());
app.use(cookie_parser());
app.use(session({
secret: "asd",
store: new mongo_store({
mongoose_connection: mongoose_connection
// db: mongoose_connection.db
})
}));
app.get("/rest/test",function(req, res) {
req.session.asd="test";
res.send(req.session.asd)
});
app.listen(...
});