sanja sanja - 5 months ago 31
Node.js Question

console.log and redirect in node.js doesn't work?

I make application to register and login, but something is not working properly

this is users.js from routers/users.js

var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var multer = require('multer');
var upload = multer({dest: './uploads'});

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

/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});

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

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

router.post('/register', upload.single('profileimage'), function(req, res, next){
//get form values
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;

//check for image field
if(req.files && req.files.profileimage){
console.log('Uploading File...');
//var profileimage = req.file.filename;

//file info
var profileImageOriginalName = req.files.profileimage.originalname;

var profileImageName = req.files.profileimage.name;
var profileImageMime = req.files.profileimage.mimetype;
var profileImagePath = req.files.profileimage.path;
var profileImageExt = req.files.profileimage.extension;
var profileImageSize = req.files.profileimage.size;
} else {
//set a default image
var profileImageName = 'noimage.png';
}

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

//check for errors
var errors = req.validationErrors();

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

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

//success message
req.flash('success', 'You are now registered and may log in');

res.location('/');
res.redirect('/');
}

});

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

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

passport.use(new LocalStrategy(
function(username, password, done){
User.getUserByUsername(username, function(err, user){
if(err) throw err;
if(!user){
console.log('Unknown 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 {
console.log('Invalid Password');
return done(null, false, {message: 'Invalid Password'});
}
});
});
}
));

router.post('/login', passport.authenticate('local',{failureRedirect: '/users/login', failureFlash: 'Invalid username or password'}), function(req, res){
console.log('Authentication Successful');
req.flash('success', 'You are logged in');
res.redirect('/');
});

module.exports = router;


and this is user.js from models/user.js

var mongoose = require('mongoose');
var bcrypt = require('bcrypt');

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

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

var User = module.exports = mongoose.model('User', UserSchema);

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

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

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

module.exports.createUser = function(newUser, callback){
bcrypt.hash(newUser.password, 10, function(err, hash){
if(err) throw err;
//set hashed pw
newUser.password = hash;
//create user
newUser.save(callback);
});
}


When using a registration, it works, however, when using the login does not work. Concretely does not show me in cmd whether I was right or not logs, and the redirect function does not work.

comand prompt

Answer

I may be wrong, but it seems that passport.authenticate breaks multiple callbacks chain. Try to wrap multiple callbacks in a single:

router.post('/login', function(req, res){
  passport.authenticate('local',{failureRedirect: '/users/login', failureFlash: 'Invalid username or password'})
  console.log('Authentication Successful');
  req.flash('success', 'You are logged in');
  res.redirect('/');
});
Comments