cphill cphill - 3 months ago 20
Node.js Question

PassportJS not recognizing record

I'm running into an issue trying to debug why my PassportJS authorization is not working as it should. I tried to add

console.log
to each if/else statement, but nothing is appearing in my terminal. The only reason I know that there is an issue is because I am using the correct credentials for a registered user, but I'm getting the failure redirect after submitting the form. Could this be due to the fact that I'm using a different parameter than 'username' and I'm not setting it up correctly? Do I need to pass the values from the form?

Model Index:

var Sequelize = require('sequelize');
var path = require('path');
var config = require(path.resolve(__dirname, '..', '..','./config/config.js'));
var sequelize = new Sequelize(config.database, config.username, config.password, {
host:'localhost',
port:'3306',
dialect: 'mysql'
});

sequelize.authenticate().then(function(err) {
if (!!err) {
console.log('Unable to connect to the database:', err)
} else {
console.log('Connection has been established successfully.')
}
});

var db = {}

db.User = sequelize.import(__dirname + "/user");

db.sequelize = sequelize;
db.Sequelize = Sequelize;

sequelize.sync();

module.exports = db;


user.js:

module.exports = function(sequelize, DataTypes) {

var User = sequelize.define('users', {
annotation_id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
firstName: {
type: DataTypes.STRING,
field: 'first_name'
},
lastName: {
type: DataTypes.STRING,
field: 'last_name'
},
email: DataTypes.STRING,
password: DataTypes.STRING,

}, {
freezeTableName: true,
instanceMethods: {
generateHash: function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
},
validPassword: function(password) {
return bcrypt.compareSync(password, this.password);
},
}
});
return User;
}


Routes:

var express = require('express');
var siteRoutes = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var models = require('../models/db-index');

/*==== Passport Configuration ====*/

// Serialize sessions
passport.serializeUser(function(user, done) {
done(null, user.id);
});

passport.deserializeUser(function(id, done) {
db.User.find({where: {id: id}}).success(function(user){
done(null, user);
}).error(function(err){
done(err, null);
});
});


passport.use(new LocalStrategy({
passReqToCallback : true,
usernameField: 'email',
passwordField : 'password'
}, function(username, password, done) {
//Find user by email
User.findOne({ username: username }, function(err, user) {
//If there is an error, return done
if (err) { return done(err); }
//If user does not exist, log error and redirect
if (!user) {
console.log('No email')
return done(null, false, { message: 'Incorrect username.' });
}
//If user exists, but wrong password
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
console.log('Password fail');
}
//If all credentials match, return user
return done(null, user);
console.log('Successful login');
});
}
));


/*==== Index ====*/

siteRoutes.get('/', function(req, res){
res.render('pages/index.hbs');
});

/*==== Login ====*/


siteRoutes.route('/login')

.get(function(req, res){
res.render('pages/login.hbs');
})

.post(passport.authenticate('local', {
successRedirect: '/app',
failureRedirect: '/',
failureFlash: true
}));



siteRoutes.route('/sign-up')

.get(function(req, res){
res.render('pages/sign-up.hbs');
})

.post(function(req, res){

models.User.create({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: req.body.password
}).then(function() {
res.redirect('/');
}).catch(function(error){
res.send(error);
})

});



module.exports = siteRoutes;


Login Form:

<!DOCTYPE html>
<head>
{{> head}}
</head>
<body>
{{> navigation}}
<div class="container">
<div class="col-md-6 col-md-offset-3">
<form action="/login" method="post">
<label for="login-username">Username</label>
<input type="text" class="form-control" id="login-username" name="username" placeholder="username or email">
<br />
<label for="login-password">Password</label>
<input type="password" class="form-control" id="login-password" name="password">
<div class="login-buttons">
<button type="submit">Login</button>
</div>
</form>
<a href="/sign-up">Don't have an account? Then register here!</a>
<br />
<a href="#">Forgot your password?</a>
</div>
</div>
</body>

Answer

You specified e-mail as login attribute but used 'username'.

User.findOne({ username: username }

As I see there is no field named username in User model.

I think, you should change username to email.

User.findOne({ email: username }