jwalkerman jwalkerman - 1 month ago 13
Node.js Question

Login system with nodeJS

I have my login system up on localhost and register page is working but not the login page. It keep showing me invalid password.
btw i am using mongodb as my database.
On my mongodb, i'm able to view those data that have been stored on the mongo shell.

I appreciate those who are able to review those codes. Thanks!!

Image:
showing invalid password image

here are my code:

app.js

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/loginapp');
var db = mongoose.connection;

var routes = require('./routes/index');
var users = require('./routes/users');

//Init App
var app = express();

//View Engine
app.set('views', path.join(__dirname, 'views')); //handle view
app.engine('handlebars', exphbs({defaultLayout:'layout'})); //set default view to layout
app.set('view engine', 'handlebars'); //set view engine to handlebars

//BodyParser Middleware (Configuration)
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());

//Set static folder (public folder.. stylesheet,images)
app.use(express.static(path.join(__dirname, 'public')));

//Express Session (Middleware for express session)
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));

//Passport init
app.use(passport.initialize());
app.use(passport.session());

//Express Validator (Middleware for validator)
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;

while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
//connect flash
app.use(flash());

//Global Vars (global func)
app.use(function (req, res,next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});

//Middleware for route files
app.use('/', routes); //map to routes index files
app.use('/users', users);

//Set Port (start the server)
app.set('port', (process.env.PORT || 3000));

app.listen(app.get('port'), function(){
console.log('Sever started on port '+app.get('port'));
});


routes/users

var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

var User = require('../models/user');

// Register
router.get('/register', function(req, res){
res.render('register');
});

// Login
router.get('/login', function(req, res){
res.render('login');
});

// Register User
router.post('/register', function(req, res){
//Get all the stuff into variable
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;

//Validation
req.checkBody('name', 'Name is required').notEmpty();
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
req.checkBody('username', 'Username is required').notEmpty();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('password2', 'Passwords do not match').equals(req.body.password);

var errors = req.validationErrors();

if(errors){
res.render('register',{
errors:errors
});
} else {
var newUser = new User({
name: name,
email: email,
username: username,
password: password
});

User.createUser(newUser, function(err, user){
if(err) throw err;
console.log(user);
});

req.flash('success_msg', 'You are registed and can now login');

res.redirect('/users/login');
}
});

passport.use(new LocalStrategy(
function(username, password, done) {
User.getUserByUsername(username, function(err, user){
if(err) throw err;
if(!user){
return done(null, false, {message: 'Unknown User'});
}

User.comparePassword(password, user.password, function(err, isMatch){
if(err) throw err;
if(isMatch){
return done(null, user);
} else {
return done(null, false, {message: 'Invalid password'});
}
});
});
}));

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

passport.deserializeUser(function(id, done) {
User.getUserById(id, function(err, user) {
done(err, user);
});
});


router.post('/login',
passport.authenticate('local', {successRedirect:'/', failureRedirect:'/users/login',failureFlash: true}),
function(req, res) {
res.redirect('/');
});

router.get('/logout', function(req, res){
req.logout();

req.flash('success_msg', 'You are logged out');

res.redirect('/users/login');
});

module.exports = router;


models/user

var mongoose = require('mongoose');
//hash password
var bcrypt = require('bcryptjs');

//User schema
var UserSchema = mongoose.Schema({
username: {
type: String,
index: true
},
password: {
type: String
},
email: {
type: String
},
name: {
type: String
}
});

//Variable that can access outside this file
var User = module.exports = mongoose.model('User', UserSchema);

//User function
module.exports.createUser = function(newUser, callback) {
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash("newUser.password", salt, function(err, hash) {
newUser.password = hash;
newUser.save(callback);
});
});
}

module.exports.getUserByUsername = function(username, callback){
var query = {username: username};
User.findOne(query, callback);
}

module.exports.getUserById = function(id, callback){
User.findById(id, callback);
}

module.exports.comparePassword = function(candidatePassword, hash, callback){
bcrypt.compare(candidatePassword, hash, function(err, isMatch) {
if(err) throw err;
callback(null, isMatch);
});
}

Answer

You have a mistake here

module.exports.createUser = function(newUser, callback) {
        bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash("newUser.password", salt, function(err, hash) {
            newUser.password = hash;
            newUser.save(callback);
        });
    });
}

It must be

bcrypt.hash(newUser.password, salt, function(err, hash) {
//__________^______________^ removed quotes
    newUser.password = hash;
    newUser.save(callback);
});

For that reason when user registers, it's password was set "newUser.password", but not actually user's password