Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS express-validator with passport

I write a signup form table, and I use passport-local is work, but I want add express-validator to validate my form data. I add validation on the router, this is my router/index.js code:

/* Handle Registration POST */
router.post('/signup', function(req, res) {
  req.assert('email', 'A valid email is required').isEmail();
  var errors = req.validationErrors();

  if(errors){   //No errors were found.  Passed Validation!
      res.render('register', {
        message: 'Mail type fault',
        errors: errors
      });
  }
  else
  {
    passport.authenticate('signup', {
      successRedirect: '/home',
      failureRedirect: '/signup',
      failureFlash : true
    });
  }
});

The validation is work, but if successful and then the web page will loading for a long time and no respond. I have search the passport doc, but no idea to fix it.

This is origin code, it's work

/* Handle Registration POST */
router.post('/signup', passport.authenticate('signup', {
  successRedirect: '/home',
  failureRedirect: '/signup',
  failureFlash : true
}));

I think I can use jquery to check out, but I don't do it. Because I just want to try use validator with passport.

like image 262
lighter Avatar asked Dec 04 '22 05:12

lighter


2 Answers

Putting validation code in LocalStartegy should work but, personally I would first do authentication and once it has passed use passport.

Consider something the following:

router.post('/login',function(req,res){

    req.checkBody('username', 'Username is required').notEmpty();
    req.checkBody('password', 'Password is required').notEmpty();

    //validate 
    var errors = req.validationErrors();

    if (errors) {

        res.render('signup',{user:null,frm_messages:errors});

    }
    else{
        passport.authenticate('login',{
            successRedirect:'/',
            failureRedirect: '/login',
            failureFlash : true  
        })(req,res); // <---- ADDD THIS
    }
});
like image 59
yeahdixon Avatar answered Dec 25 '22 08:12

yeahdixon


/* Handle Registration POST */
router.post('/signup', checkEmail,
    passport.authenticate('signup', {
      successRedirect: '/home',
      failureRedirect: '/signup',
      failureFlash : true
    });
});

function checkEmail(req, res, next){
    req.checkBody('username', 'Username is required').notEmpty();
    req.checkBody('password', 'Password is required').notEmpty();
    //validate 
    var errors = req.validationErrors();
    if (errors) {
        res.render('signup',{user:null,frm_messages:errors});
    } else {
      next();
    }
}
like image 39
Anatoliy Pechkin Avatar answered Dec 25 '22 07:12

Anatoliy Pechkin