Filipe Ferminiano Filipe Ferminiano - 19 days ago 7
Node.js Question

Unable to signup users with passport-local

I'm trying to use a local passport to login and signup in my app.

But when I send a post request from my signup form, the user is being redirected to the signup form.

This is the route definition:

app.post('/signup', passport.authenticate('local-signup', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/signup', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));


This is my config/passport.js

var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user');
var mysql = require('mysql');
var connection = mysql.createConnection({
host : process.env.MYSQL_HOST,
user : process.env.MYSQL_USER,
password : process.env.MYSQL_PASSWORD,
database : process.env.MYSQL_DB
});

module.exports = function(passport) {
passport.serializeUser(function(user, done) {
console.log("abc serializeUser");
console.log(user);
done(null, user.id);
});

passport.deserializeUser(function(id, done) {
console.log("abc deserializeUser");
User.findById(id).then(function(user){
done(null, user);
}).catch(function(e){
done(e, false);
});
});

passport.use('local-signup', new LocalStrategy(

function(username, password, done) {
console.log("abc local signup");
User.findOne({where: {username: username}}).then(function(err, user) {
if (err) { return done(err); }
if (!user) {
console.log('Incorrect username.');
return done(null, false, { message: 'Incorrect username.' });
} else if (password != user.password) {
console.log('Incorrect password');
return done(null, false, { message: 'Incorrect password.' });
} else {
console.log('ok');
done(null, user);
}
});

}

));

};


This is the models/user.js

"use strict";

module.exports = function(sequelize, DataTypes) {
var User = sequelize.define("User", {
email: DataTypes.STRING,
password: DataTypes.STRING,
token: DataTypes.STRING
}

);

return User;
};

Answer

Sequelize's .then() receives result only, errors should be handled by .catch() block. So the query will looks like this:

        User.findOne({where: {username: username}}).then(function(user) {
           if (!user) {
               console.log('Incorrect username.');
               return done(null, false, { message: 'Incorrect username.' });
           } else if (password != user.password) {
               console.log('Incorrect password');
               return done(null, false, { message: 'Incorrect password.' });
           } else {
               console.log('ok');
               done(null, user);
           }
        }).catch(function(err){
           done(err);
        });