passwordValidator option in passport local mongoose doesn't work





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I am trying to validate password, during registration process, with passport local mongoose but it doesn't work. It doesn't throw an error but when I register with a password that does not fit the validation criteria, it gets accepted. Here is the UserSchema:



var UserSchema = new mongoose.Schema({
email: {
type: String,
unique: true
},
password: String,
displayname: String,
firstName: String,
lastName: String,
resetPasswordToken: String,
resetPasswordExpires: Date,
avatar: String,
Bio: String,
isAdmin: {type: Boolean, default: false}

});

var passwordValidator = function(password, cb){
var regex = /^(?=.*d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
if(!password.match(regex)){
return cb(null, false)
}
return cb(null, true);
}

UserSchema.plugin(passportLocalMongoose, {
usernameField: "email",
errorMessages: {
IncorrectPasswordError: "Password incorrect",
IncorrectUsernameError: "There is no account registered with that email",
UserExistsError: "A user with the given email is already registered"
},
passwordValidator: passwordValidator
});
module.exports = mongoose.model("User", UserSchema);


Registration code:



router.post("/register", upload.single("avatar"), function(req, res){
cloudinary.v2.uploader.upload(req.file.path, function(err, result){
if(err) {
req.flash("error", err.message);
return res.redirect("back");
}
var newUser = new User({displayname: req.body.displayname,
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
Bio: req.body.bio,
avatar : result.secure_url
});

if(req.body.adminCode === "secretcode123"){
newUser.isAdmin = true;
}



User.register(newUser, req.body.password, function(err, user){
if(err){
console.log(err);
req.flash("error", err.message);
return res.redirect("/register");
}

passport.authenticate("local")(req,res, function(){
req.flash("success", "Welcome " + " " + user.displayname);
res.redirect("/campground");
})
});
})


How do I get it to validate the password?










share|improve this question





























    0















    I am trying to validate password, during registration process, with passport local mongoose but it doesn't work. It doesn't throw an error but when I register with a password that does not fit the validation criteria, it gets accepted. Here is the UserSchema:



    var UserSchema = new mongoose.Schema({
    email: {
    type: String,
    unique: true
    },
    password: String,
    displayname: String,
    firstName: String,
    lastName: String,
    resetPasswordToken: String,
    resetPasswordExpires: Date,
    avatar: String,
    Bio: String,
    isAdmin: {type: Boolean, default: false}

    });

    var passwordValidator = function(password, cb){
    var regex = /^(?=.*d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
    if(!password.match(regex)){
    return cb(null, false)
    }
    return cb(null, true);
    }

    UserSchema.plugin(passportLocalMongoose, {
    usernameField: "email",
    errorMessages: {
    IncorrectPasswordError: "Password incorrect",
    IncorrectUsernameError: "There is no account registered with that email",
    UserExistsError: "A user with the given email is already registered"
    },
    passwordValidator: passwordValidator
    });
    module.exports = mongoose.model("User", UserSchema);


    Registration code:



    router.post("/register", upload.single("avatar"), function(req, res){
    cloudinary.v2.uploader.upload(req.file.path, function(err, result){
    if(err) {
    req.flash("error", err.message);
    return res.redirect("back");
    }
    var newUser = new User({displayname: req.body.displayname,
    firstName: req.body.firstName,
    lastName: req.body.lastName,
    email: req.body.email,
    Bio: req.body.bio,
    avatar : result.secure_url
    });

    if(req.body.adminCode === "secretcode123"){
    newUser.isAdmin = true;
    }



    User.register(newUser, req.body.password, function(err, user){
    if(err){
    console.log(err);
    req.flash("error", err.message);
    return res.redirect("/register");
    }

    passport.authenticate("local")(req,res, function(){
    req.flash("success", "Welcome " + " " + user.displayname);
    res.redirect("/campground");
    })
    });
    })


    How do I get it to validate the password?










    share|improve this question

























      0












      0








      0








      I am trying to validate password, during registration process, with passport local mongoose but it doesn't work. It doesn't throw an error but when I register with a password that does not fit the validation criteria, it gets accepted. Here is the UserSchema:



      var UserSchema = new mongoose.Schema({
      email: {
      type: String,
      unique: true
      },
      password: String,
      displayname: String,
      firstName: String,
      lastName: String,
      resetPasswordToken: String,
      resetPasswordExpires: Date,
      avatar: String,
      Bio: String,
      isAdmin: {type: Boolean, default: false}

      });

      var passwordValidator = function(password, cb){
      var regex = /^(?=.*d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
      if(!password.match(regex)){
      return cb(null, false)
      }
      return cb(null, true);
      }

      UserSchema.plugin(passportLocalMongoose, {
      usernameField: "email",
      errorMessages: {
      IncorrectPasswordError: "Password incorrect",
      IncorrectUsernameError: "There is no account registered with that email",
      UserExistsError: "A user with the given email is already registered"
      },
      passwordValidator: passwordValidator
      });
      module.exports = mongoose.model("User", UserSchema);


      Registration code:



      router.post("/register", upload.single("avatar"), function(req, res){
      cloudinary.v2.uploader.upload(req.file.path, function(err, result){
      if(err) {
      req.flash("error", err.message);
      return res.redirect("back");
      }
      var newUser = new User({displayname: req.body.displayname,
      firstName: req.body.firstName,
      lastName: req.body.lastName,
      email: req.body.email,
      Bio: req.body.bio,
      avatar : result.secure_url
      });

      if(req.body.adminCode === "secretcode123"){
      newUser.isAdmin = true;
      }



      User.register(newUser, req.body.password, function(err, user){
      if(err){
      console.log(err);
      req.flash("error", err.message);
      return res.redirect("/register");
      }

      passport.authenticate("local")(req,res, function(){
      req.flash("success", "Welcome " + " " + user.displayname);
      res.redirect("/campground");
      })
      });
      })


      How do I get it to validate the password?










      share|improve this question














      I am trying to validate password, during registration process, with passport local mongoose but it doesn't work. It doesn't throw an error but when I register with a password that does not fit the validation criteria, it gets accepted. Here is the UserSchema:



      var UserSchema = new mongoose.Schema({
      email: {
      type: String,
      unique: true
      },
      password: String,
      displayname: String,
      firstName: String,
      lastName: String,
      resetPasswordToken: String,
      resetPasswordExpires: Date,
      avatar: String,
      Bio: String,
      isAdmin: {type: Boolean, default: false}

      });

      var passwordValidator = function(password, cb){
      var regex = /^(?=.*d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
      if(!password.match(regex)){
      return cb(null, false)
      }
      return cb(null, true);
      }

      UserSchema.plugin(passportLocalMongoose, {
      usernameField: "email",
      errorMessages: {
      IncorrectPasswordError: "Password incorrect",
      IncorrectUsernameError: "There is no account registered with that email",
      UserExistsError: "A user with the given email is already registered"
      },
      passwordValidator: passwordValidator
      });
      module.exports = mongoose.model("User", UserSchema);


      Registration code:



      router.post("/register", upload.single("avatar"), function(req, res){
      cloudinary.v2.uploader.upload(req.file.path, function(err, result){
      if(err) {
      req.flash("error", err.message);
      return res.redirect("back");
      }
      var newUser = new User({displayname: req.body.displayname,
      firstName: req.body.firstName,
      lastName: req.body.lastName,
      email: req.body.email,
      Bio: req.body.bio,
      avatar : result.secure_url
      });

      if(req.body.adminCode === "secretcode123"){
      newUser.isAdmin = true;
      }



      User.register(newUser, req.body.password, function(err, user){
      if(err){
      console.log(err);
      req.flash("error", err.message);
      return res.redirect("/register");
      }

      passport.authenticate("local")(req,res, function(){
      req.flash("success", "Welcome " + " " + user.displayname);
      res.redirect("/campground");
      })
      });
      })


      How do I get it to validate the password?







      node.js mongoose passport-local






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 22 '18 at 11:48









      R. WanjohiR. Wanjohi

      264




      264
























          2 Answers
          2






          active

          oldest

          votes


















          0














          You didn't define Passport local strategy for passport-local-mongoose, that's why you are getting like that.Hence your code doesn't have anything to compare your password with. So without any local strategy, authentication will be success full every time.



          If you are using Passport-local-mongoose ,it will create a salt and hash itself by using the given password. Hence you don't have to store your password in mongoose.
          User.register()
          is a default passport-local-mongoose function for that.
          So your user schema should look like



              var UserSchema = new mongoose.Schema({
          email: {
          type: String,
          unique: true
          },
          name:String,
          address: String});


          See here i didn't mentioned password in user schema.



          Then you should define your passport-local strategy. For Passport-local-mongoose it should be like



          passport.use(new LocalStrategy(User.authenticate()));
          where user is your exported usershema.



          If you are not using passport-local-mongoose, then local strategy code will be different, not like the one given above.



          Then you should do serialise and deserialize your passport. It is like this for passport-local-mongoose



           passport.serializeUser(User.serializeUser());
          passport.deserializeUser(User.deserializeUser());


          I think you already know to initialise passport like this



          app.use(passport.initialize());     
          app.use(passport.session())


          now its time for authentication. Code is



            `passport.authenticate('local',function (err, user, info) { if(err){
          res.redirect("/register");
          } else{
          if (! user) {
          res.redirect("/register");
          } else{
          req.login(user, function(err){
          if(err){
          res.redirect("/register");
          }else{
          res.redirect("/campground");`
          }
          })
          }
          }
          })(req, res);`


          If you want to display the error message from passport-local-mongoose you can console the info from passport.authenticate.



          If you want to know more details go through https://github.com/saintedlama/passport-local-mongoose






          share|improve this answer

































            0














            If you are using passport-local-mongoose, the module itself will create an salt and hash and it will compare the password itself while authentication. You dont have to write password validator for that.






            share|improve this answer
























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53430352%2fpasswordvalidator-option-in-passport-local-mongoose-doesnt-work%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              0














              You didn't define Passport local strategy for passport-local-mongoose, that's why you are getting like that.Hence your code doesn't have anything to compare your password with. So without any local strategy, authentication will be success full every time.



              If you are using Passport-local-mongoose ,it will create a salt and hash itself by using the given password. Hence you don't have to store your password in mongoose.
              User.register()
              is a default passport-local-mongoose function for that.
              So your user schema should look like



                  var UserSchema = new mongoose.Schema({
              email: {
              type: String,
              unique: true
              },
              name:String,
              address: String});


              See here i didn't mentioned password in user schema.



              Then you should define your passport-local strategy. For Passport-local-mongoose it should be like



              passport.use(new LocalStrategy(User.authenticate()));
              where user is your exported usershema.



              If you are not using passport-local-mongoose, then local strategy code will be different, not like the one given above.



              Then you should do serialise and deserialize your passport. It is like this for passport-local-mongoose



               passport.serializeUser(User.serializeUser());
              passport.deserializeUser(User.deserializeUser());


              I think you already know to initialise passport like this



              app.use(passport.initialize());     
              app.use(passport.session())


              now its time for authentication. Code is



                `passport.authenticate('local',function (err, user, info) { if(err){
              res.redirect("/register");
              } else{
              if (! user) {
              res.redirect("/register");
              } else{
              req.login(user, function(err){
              if(err){
              res.redirect("/register");
              }else{
              res.redirect("/campground");`
              }
              })
              }
              }
              })(req, res);`


              If you want to display the error message from passport-local-mongoose you can console the info from passport.authenticate.



              If you want to know more details go through https://github.com/saintedlama/passport-local-mongoose






              share|improve this answer






























                0














                You didn't define Passport local strategy for passport-local-mongoose, that's why you are getting like that.Hence your code doesn't have anything to compare your password with. So without any local strategy, authentication will be success full every time.



                If you are using Passport-local-mongoose ,it will create a salt and hash itself by using the given password. Hence you don't have to store your password in mongoose.
                User.register()
                is a default passport-local-mongoose function for that.
                So your user schema should look like



                    var UserSchema = new mongoose.Schema({
                email: {
                type: String,
                unique: true
                },
                name:String,
                address: String});


                See here i didn't mentioned password in user schema.



                Then you should define your passport-local strategy. For Passport-local-mongoose it should be like



                passport.use(new LocalStrategy(User.authenticate()));
                where user is your exported usershema.



                If you are not using passport-local-mongoose, then local strategy code will be different, not like the one given above.



                Then you should do serialise and deserialize your passport. It is like this for passport-local-mongoose



                 passport.serializeUser(User.serializeUser());
                passport.deserializeUser(User.deserializeUser());


                I think you already know to initialise passport like this



                app.use(passport.initialize());     
                app.use(passport.session())


                now its time for authentication. Code is



                  `passport.authenticate('local',function (err, user, info) { if(err){
                res.redirect("/register");
                } else{
                if (! user) {
                res.redirect("/register");
                } else{
                req.login(user, function(err){
                if(err){
                res.redirect("/register");
                }else{
                res.redirect("/campground");`
                }
                })
                }
                }
                })(req, res);`


                If you want to display the error message from passport-local-mongoose you can console the info from passport.authenticate.



                If you want to know more details go through https://github.com/saintedlama/passport-local-mongoose






                share|improve this answer




























                  0












                  0








                  0







                  You didn't define Passport local strategy for passport-local-mongoose, that's why you are getting like that.Hence your code doesn't have anything to compare your password with. So without any local strategy, authentication will be success full every time.



                  If you are using Passport-local-mongoose ,it will create a salt and hash itself by using the given password. Hence you don't have to store your password in mongoose.
                  User.register()
                  is a default passport-local-mongoose function for that.
                  So your user schema should look like



                      var UserSchema = new mongoose.Schema({
                  email: {
                  type: String,
                  unique: true
                  },
                  name:String,
                  address: String});


                  See here i didn't mentioned password in user schema.



                  Then you should define your passport-local strategy. For Passport-local-mongoose it should be like



                  passport.use(new LocalStrategy(User.authenticate()));
                  where user is your exported usershema.



                  If you are not using passport-local-mongoose, then local strategy code will be different, not like the one given above.



                  Then you should do serialise and deserialize your passport. It is like this for passport-local-mongoose



                   passport.serializeUser(User.serializeUser());
                  passport.deserializeUser(User.deserializeUser());


                  I think you already know to initialise passport like this



                  app.use(passport.initialize());     
                  app.use(passport.session())


                  now its time for authentication. Code is



                    `passport.authenticate('local',function (err, user, info) { if(err){
                  res.redirect("/register");
                  } else{
                  if (! user) {
                  res.redirect("/register");
                  } else{
                  req.login(user, function(err){
                  if(err){
                  res.redirect("/register");
                  }else{
                  res.redirect("/campground");`
                  }
                  })
                  }
                  }
                  })(req, res);`


                  If you want to display the error message from passport-local-mongoose you can console the info from passport.authenticate.



                  If you want to know more details go through https://github.com/saintedlama/passport-local-mongoose






                  share|improve this answer















                  You didn't define Passport local strategy for passport-local-mongoose, that's why you are getting like that.Hence your code doesn't have anything to compare your password with. So without any local strategy, authentication will be success full every time.



                  If you are using Passport-local-mongoose ,it will create a salt and hash itself by using the given password. Hence you don't have to store your password in mongoose.
                  User.register()
                  is a default passport-local-mongoose function for that.
                  So your user schema should look like



                      var UserSchema = new mongoose.Schema({
                  email: {
                  type: String,
                  unique: true
                  },
                  name:String,
                  address: String});


                  See here i didn't mentioned password in user schema.



                  Then you should define your passport-local strategy. For Passport-local-mongoose it should be like



                  passport.use(new LocalStrategy(User.authenticate()));
                  where user is your exported usershema.



                  If you are not using passport-local-mongoose, then local strategy code will be different, not like the one given above.



                  Then you should do serialise and deserialize your passport. It is like this for passport-local-mongoose



                   passport.serializeUser(User.serializeUser());
                  passport.deserializeUser(User.deserializeUser());


                  I think you already know to initialise passport like this



                  app.use(passport.initialize());     
                  app.use(passport.session())


                  now its time for authentication. Code is



                    `passport.authenticate('local',function (err, user, info) { if(err){
                  res.redirect("/register");
                  } else{
                  if (! user) {
                  res.redirect("/register");
                  } else{
                  req.login(user, function(err){
                  if(err){
                  res.redirect("/register");
                  }else{
                  res.redirect("/campground");`
                  }
                  })
                  }
                  }
                  })(req, res);`


                  If you want to display the error message from passport-local-mongoose you can console the info from passport.authenticate.



                  If you want to know more details go through https://github.com/saintedlama/passport-local-mongoose







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Feb 26 at 8:13

























                  answered Feb 26 at 7:21









                  Pran R.VPran R.V

                  3117




                  3117

























                      0














                      If you are using passport-local-mongoose, the module itself will create an salt and hash and it will compare the password itself while authentication. You dont have to write password validator for that.






                      share|improve this answer




























                        0














                        If you are using passport-local-mongoose, the module itself will create an salt and hash and it will compare the password itself while authentication. You dont have to write password validator for that.






                        share|improve this answer


























                          0












                          0








                          0







                          If you are using passport-local-mongoose, the module itself will create an salt and hash and it will compare the password itself while authentication. You dont have to write password validator for that.






                          share|improve this answer













                          If you are using passport-local-mongoose, the module itself will create an salt and hash and it will compare the password itself while authentication. You dont have to write password validator for that.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Apr 2 at 4:32









                          Pran R.VPran R.V

                          3117




                          3117






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53430352%2fpasswordvalidator-option-in-passport-local-mongoose-doesnt-work%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Guess what letter conforming each word

                              Port of Spain

                              Run scheduled task as local user group (not BUILTIN)