Nodejs passport authentication hanging - node.js

I'm following a nodejs book here: https://www.packtpub.com/web-development/mean-web-development
All is going smoothly until I try and log in using the passport module. It just hangs with no errors. I have tried other solutions I've found on SO such as re-ordering the middleware, but I think they might be for different versions of Express, as some of the syntax looks slightly different (and doesn't work). Here are the relevant parts. Any help would be greatly appreciated!
Package.json:
{
"name": "MEAN",
"version": "0.0.3",
"description": "First mean app",
"dependencies": {
"express": "~4.8.8",
"morgan": "~1.3.0",
"compression": "~1.0.11",
"body-parser": "~1.8.0",
"method-override": "~2.2.0",
"express-session": "~1.7.6",
"ejs": "~1.0.0",
"connect-flash": "~0.1.1",
"mongoose": "~3.8.15",
"passport": "~0.2.1",
"passport-local": "~1.0.0"
}
}
express.js:
module.exports = function(){
var app = express();
if(process.env.NODE_ENV === 'development'){
app.use(morgan('dev'));
}else if(process.env.NODE_ENV === 'production'){
app.use(compress());
}
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(session({
saveUnitialized: true,
resave: true,
secret: config.sessionSecret
}));
app.set('views', './app/views');
app.set('view engine', 'ejs');
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
require('../app/routes/index.server.routes.js')(app);
require('../app/routes/users.server.routes.js')(app);
app.use(express.static('./public'));
return app;
};
passport.js
module.exports = function(){
var User = mongoose.model('User');
passport.serializeUser(function(user, done){
done(null, user.id);
});
passport.deserializeUser(function(id, done){
User.findOne({
_id: id
}, '-password -salt'), function(err, user){
done(err, user);
};
});
require('./strategies/local.js')();
};
the routing:
app.route('/signin')
.get(users.renderSignin)
.post(passport.authenticate('local',{
successRedirect: '/',
failureRedirect: '/signin',
failureFlash: true
}));
Edit: it seems to be the passport.deserializeUser function where things break

Well I've gone to the passport docs, and pasted in the code from there, and it seems to work. So... any idea why the MEAN book example isn't working?
Code that worked:
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});

Related

nodejs express-session middleware is not working in visual studio

I'm trying to use express-session in nodejs express but I can't set or get sessions. I get "Property 'session' does not exist on type 'Request'" when I'm trying to build.
I tried to change the order of the codes but nothing works
node version : v10.15.3
visual studio : 2017
my dependencies
"dependencies": {
"axios": "^0.19.0",
"body-parser": "^1.19.0",
"cookie-parser": "^1.4.4",
"debug": "^2.2.0",
"express": "^4.14.0",
"express-session": "^1.16.2",
"pug": "^2.0.0-rc.3",
"session-file-store": "^1.3.0"
},
"devDependencies": {
"#types/debug": "0.0.30",
"#types/express": "^4.0.37",
"#types/express-serve-static-core": "^4.0.50",
"#types/mime": "^1.3.1",
"#types/serve-static": "^1.7.32",
"#types/node": "^6.0.87"
}
app.ts
var app = express();
var bodyParser = require('body-parser');
var session = require('express-session');
var FileStore = require('session-file-store')(session);
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(express.json()); // to support JSON-encoded bodies
app.use(express.urlencoded({ extended: true })); // to support URL-encoded bodies
app.use(session({
name: 'test-session-cookie-id',
secret: 'test',
resave: true,
store: new FileStore(),
saveUninitialized: true,
cookie: { secure: true }
}));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/signup', signup);
app.use('/verify', verify);
app.use(function printSession(req, res, next) {
console.log('req.session', req.session); //error
return next();
});
update :
module seems to be working fine itself . it created a session folder with 500+ files which is odd
update2 :
the express session is working fine but the error is bugging me. I uninstalled vs2017 and installed vs2019 and updated the typescript but the problem is still there
there was no #types/express-session in my dependencies/devDependencies . npm install --save #types/express-session did the job . there is no error now

Session using NodeJS and Express 4.x (req.session undefined)

First of all sorry my bad English. I'm studying and I'm doing an academic project and came across a problem. I can not recall a session variable.
package.json
"dependencies": {
"body-parser": "^1.7.0",
"ejs": "~1.0.0",
"express": "^4.8.7",
"express-session": "^1.11.3",
"ini": "^1.3.4",
"mysql": "^2.8.0",
"winston": "^1.0.1"
}
server.js
var express = require('express');
var session = require('express-session');
var app = express();
...
require('./router/main')(app, language, connection, logger);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(__dirname + '/public'));
app.use(session({
secret: 'pecuniamsekretsession',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}));
main.js
module.exports = function(app, languageItems, connection, logger) {
app.post('/', require('../router/login.js')(languageItems, connection, logger));
app.get('/', require('../router/login.js')(languageItems, connection, logger));
}
login.js
module.exports = function (language, connection, logger) {
var routerTemplateLogin = function (req, res) {
var utils = require('../utils/utils');
var util = new utils.Util;
// It does not work :-(
logger.debug(req.session);
req.on('data', function(data) {
var arrayPost = util.postDataToArray(data);
});
res.render('pages/login.ejs', {
lang: language
});
}
return routerTemplateLogin;
}
In login.js see // It does not work :-(. Full project in https://github.com/braulioti/pecuniam
Thanks
The problem is that the routes are set up before any other middleware. Move this line:
require('./router/main')(app, language, connection, logger);
after this:
app.use(session({
secret: 'pecuniamsekretsession',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}));
in your server.js.

login persistence in browser req.user (node.js, mean.io)

I'm following with tutorial "Building AngularJS and Node.js Apps with the MEAN Stack", and just stuck with
"04. Persisting Login between Page Refreshes.mp4"
As said in this part of tutorial, some middleware function must console.log req.user object. But it is not happening.
package.json's dependencies:
"body-parser": "~1.0.2",
"cookie-parser": "^1.1.0",
"express": "~4.1.2",
"express-session": "^1.1.0",
"jade": "~1.3.1",
"mongoose": "~3.8.9",
"morgan": "~1.0.1",
"passport": "^0.2.0",
"passport-local": "^1.0.0",
"serve-favicon": "~2.0.0",
"stylus": "~0.44.0"
server.js (full)
'use strict';
var express = require('express');
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var app = express();
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var config = require('./server/config/config')[env];
require('./server/config/express')(app, config);
require('./server/config/mongoose')(config);
var User = mongoose.model('User');
passport.use(new LocalStrategy(function(username, password, done) {
User.findOne({username: username}).exec(function(error, user) {
if(error) { return done(error); }
if(user && user.authenticate(password)) {
return done(null, user);
} else {
return done(null, false);
}
});
}));
// !!!! this middleware must console.log req.user, but it is always undefined.
// req.session displays and seems like correct
app.use(function(req, res, next) {
// console.log(req.session);
console.log(req.user);
next();
});
passport.serializeUser(function(user, done) {
if(user) {
done(null, user._id);
}
});
passport.deserializeUser(function(id, done) {
User.findOne({_id: id}).exec(function(error, user) {
if(!user) {
return done(null, false);
}
return done(null, user);
});
});
require('./server/config/routes')(app);
app.listen(config.port);
console.log('listening on port ' + config.port + '...');
express.js (full)
'use strict';
var express = require('express');
var stylus = require('stylus');
var logger = require('morgan');
var body_parser = require('body-parser');
var cookie_parser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var favicon = require('serve-favicon');
module.exports = function(app, config) {
app.set('views', config.root_path + '/server/views');
app.set('view engine', 'jade');
function compile(str, path){
return stylus(str).set('filename', path);
}
app.use(stylus.middleware({
src: config.root_path + '/public',
compile: compile
}));
app.use(logger());
app.use(cookie_parser('multi vision unicorns'));
app.use(session({ secret: 'keyboard cat', key: 'sid', cookie: { secure: true }}));
app.use(body_parser());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(config.root_path + '/public'));
app.use(favicon(config.root_path + '/public/favicon.ico'));
// development
// = = = = = = = = = = = =
if ('development' === app.get('env')) {
app.locals.pretty = true;
}
};
Right now I can log in using passport module via POST, but after refreshing page, state of login does not persist, and I have to log in again. In tutorial said, that this middleware
app.use(function(req, res, next) {
console.log(req.user);
next();
});
must console.log user object even after refreshing page. But in does not.
The ending goal of lesson, is to persist state of login for browser, so that field 'username', 'password', button 'Sign In' were hidden after logging in, and stayed hidden after refreshing. But seems like server does not persist state of login too. May be problem with session, may be something else.
Please help..
= = = = = = = =
Problem solved, - had to remove "cookie: { secure: true }" part from:
"app.use(session({ secret: 'secret', key: 'sid', cookie: { secure: true }}));" as it works only with https
I think you need to store the session. (Example in CoffeeScript.)
session = require 'express-session'
mongoStore = (require 'connect-mongo') session
app.use session
secret: 'super secret'
store: new mongoStore(db: 'session')
cookie:
secure: true
maxAge: 2592000000

Passportjs facebook authentication is blocking my application

Modules:
"express": "~3.0.0",
"jade": ">= 0.0.1",
"mongoose": ">= 3.6.2",
"connect-mongo": "0.3.2",
"nodemailer": ">= 0.3.20",
"socket.io": "0.9",
"cookie": "0.0.5",
"passport": "0.2.3",
"passport-facebook": "*",
"underscore": "*"
-- BACKEND --
Expressjs Configuration:
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', config.root + '/app/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.limit('1mb'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser(''));
app.use(express.session());
app.use(express.static(path.join(config.root, 'public')));
// express/mongo session storage
app.use(express.session({
secret: '',
store: new mongoStore({
url: config.db,
collection : 'sessions'
})
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
});
In routers:
app.get('/login/facebook', passport.authenticate('facebook', { display: 'popup', scope: [ 'email', 'user_about_me'], failureRedirect: '/' }));
app.get('/login/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/' }), user.callbackLogin);
In user.callbackLogin :
exports.callbackLogin = function(req, res){
res.render('callback_login');
};
callback_login view has a js script to close the window login popup.
-- FRONTEND --
Utils.popupCenter = function(url, width, height, name) {
var left = (screen.width/2)-(width/2);
var top = (screen.height/2)-(height/2);
return window.open(url, name, "menubar=no,toolbar=no,status=no,width="+width+",height="+height+",toolbar=no,left="+left+",top="+top);
};
Utils.popupCenter('login/facebook', 600, 400, 'Facebook Login');
I'm having troubles with passportjs integration. The popup works, the facebook login is called, and when I click in 'Ok' the facebook returns the data and passport saves in mongodb. But, after this point, nothings works. Expressjs blocking the requests. When I try access another url nodejs stay busy. After spends some time I'm receiving the message "No data received".
I know it's quite late for an answer, but try this project that I put up together:
https://github.com/rafaelfaria/PassportJS-Facebook-Client-Auth
I hope that's what you are looking for.

Nodejs/Express POST request middleware unable to call next() in callback

There is very strange behavior in Express, can't figure out, mind cracking problem.
So suppose in req.user I have user id and here is my middleware code.
app.use(function(req, res, next){
var User = mongoose.model('User');
User.findById(req.user, function(err, user){
if(err) return next(err);
res.locals.user = user;
console.log(user);
next();
});
}
So it is working just fine when request type is GET, but if request is POST it just get to infinite waiting, until I receive No data received.
There is no issues with database nor with session: console.log(user) always works.
This is very very strange... I even tried to use another async function and it didn't work again for POST only requests.
fs.stat(__dirname + '/schemas/user.js', function(err, stat){
next();
})
My conclusion is that if next() is being called from callback during POST request it just hangs, but who can explain me WHY???
The original issue that brings me here was when I was trying to use passport.js deserializer which reads user from mongodb for every request, so that fails too for POST only requests.
configurations
{
"name": "myApp",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "./node_modules/.bin/nodemon app.js"
},
"dependencies": {
"express": "3.0.0rc5", //did also tried with rc4
"ejs": ">= 0.8.3",
"express-partials": "latest",
"mongodb": ">= 1.1.7",
"mongoose": "*",
"node-uuid": "*",
"passport": "*",
"passport-local": "*",
"flashify": "*",
"nodemon": "latest"
}
}
express configuration
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.logger('dev'));
app.use(partials());
app.use(express.cookieParser('Secret secret'));
app.use(express.session());
app.use(passport.initialize());
app.use(passport.session());
app.use(MY_MIDDLEWARE_HERE);
app.use(express.favicon());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(flashify);
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
I'm not sure this will have an effect, but its recommended to use bodyParser middleware earlier in the middleware stack. I would put it below cookieParser and above passport middleware, since many authentication mechanisms need to find parameters in the body.

Resources