Search code examples
node.jspassport.jspassport-localexpress-validator

How to implement express-validator, which already works with REGISTER route, to work with passport-local LOGIN?


In my route's file I have

const express = require("express");
const { body, check, validationResult } = require("express-validator/check");
const passport = require("passport");
const User = require("../models/User");

which perfectly works with my registration route

router.post("/register",
    check('username').isEmail().withMessage("You need email for username registration"),
    check("password").custom((value, { req }) => {
        if (value !== req.body.password2) {
            throw new Error("Password confirmation failed")
        } else {
            return true;
        }
    }),
    (req, res) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            errors.array().forEach(err => req.flash('error', err.msg));
            return res.redirect('/register');
        }
        const newUser = new User({ username: req.body.username });
        User.register(newUser, req.body.password, (err, user) => {
            if (err) {
                console.log(err);
                return res.redirect('back');
            }
            passport.authenticate('local')(req, res, () => {
                res.redirect('/blogs');
            })
        });
    });

but I can't implement that logic in login passport route, so I basically want to know how to put express-validator in passport login logic

router.post("/login", check('username').isEmail(), passport.authenticate("local", {
    failureRedirect: "/login"
}), function (req, res) {
    req.flash('success', 'You are successfuly Sign In');
    res.redirect("/blogs");
});

Solution

  • Here is what works perfectly for me.

     router.post("/login", 
          [check('username').isEmail().withMessage("username should be an email")], 
          (req, res, next) => {
              // Check validation.
              const errors = validationResult(req);
              if (!errors.isEmpty()) {
                  errors.array().forEach(err => req.flash('error', err.msg));
                  return res.redirect('/login');
              }
              next(); 
          },
          // If validation succeeds, go on with passport authentication logic.
          passport.authenticate("local", {...
          ...
          });
     );
    

    You have to place the validation logic inside an array according to the docs, and you should do the same with the register route.