Passport.js as Custom Callback with Express-Validator >> Can't save new user to database and...












0














I've been racking my brain over this for hours :-/



I'm trying to incorporate Express Validator checks before Passport authenticate in order for a new user to signup/register.



From reading online and a ton of tutorials I understand Passport needs to be used as custom callback (http://www.passportjs.org/docs/authenticate/) if valdidate checks are to be used first. However I've tried many different options and either the checks work and passport authenticates with no new user added to the mongodb database, or I can register a new user email despite that user email already existing.



Any help is much appreciated! Please let me know if you need more code/info from me. Thanks in advance!



User.js file



var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var userSchema = mongoose.Schema({

local : {
email : String,
password : String,
fname : String,
lname : String,
role : String,
}

});

// generating a hash =============
userSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(12), null);
};

// checking if password is valid
userSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};



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


Passport.js file



passport.use('local-signup', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true },


function(req, password, email, done) {
//specify new variables (As well as password & email already captured in function)
var fname = req.body.fname;
var lname = req.body.lname;
var role = req.body.role;


User.findOne({ 'local.email' : email }, function(err, user, req) {
// if there are any errors, return the error
if (err)
return done(err);

// check to see if theres already a user with that email
if (user) {
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
} else {

// if there is no user with that email
// create the user
var newUser = new User();

// set the user's local credentials
newUser.local.email = email;
newUser.local.password = newUser.generateHash(password);
newUser.local.fname = fname;
newUser.local.lname = lname;
newUser.local.role = role;
// save the user
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
}));


Routes.js file



 app.post('/signup',

check('email')
.not().isEmpty().withMessage('Please specify an email.')
.isEmail().withMessage('Incorrect email format.'),
check('password')
.not().isEmpty().withMessage('Please specify a password.')
.matches(/^(?=.*d)(?=.*[a-z])(?=.*[A-Z])(?!.* )(?=.*[^a-zA-Z0-9]).{8,}$/, 'i').withMessage('Password must include 1 uppercase character, 1 number and 1 special character')
.isLength({min: 8, max: 100}).withMessage('Password must be at least 8 characters in length.'),
check('fname')
.not().isEmpty().withMessage('Please enter your first name.'),
check('lname')
.not().isEmpty().withMessage('Please enter your last name.'),
check('role')
.not().isEmpty().withMessage('Please state your role.'),

function(req, res, next) {
var errors = validationResult(req);
if (!errors.isEmpty()) {
return res.render('signup.html', {message: errors.array()[0].msg});
} else {

passport.authenticate('local-signup', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/signup'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/profile');
});
})(req, res, next);
};
});









share|improve this question





























    0














    I've been racking my brain over this for hours :-/



    I'm trying to incorporate Express Validator checks before Passport authenticate in order for a new user to signup/register.



    From reading online and a ton of tutorials I understand Passport needs to be used as custom callback (http://www.passportjs.org/docs/authenticate/) if valdidate checks are to be used first. However I've tried many different options and either the checks work and passport authenticates with no new user added to the mongodb database, or I can register a new user email despite that user email already existing.



    Any help is much appreciated! Please let me know if you need more code/info from me. Thanks in advance!



    User.js file



    var mongoose = require('mongoose');
    var bcrypt = require('bcrypt-nodejs');
    var userSchema = mongoose.Schema({

    local : {
    email : String,
    password : String,
    fname : String,
    lname : String,
    role : String,
    }

    });

    // generating a hash =============
    userSchema.methods.generateHash = function(password) {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(12), null);
    };

    // checking if password is valid
    userSchema.methods.validPassword = function(password) {
    return bcrypt.compareSync(password, this.local.password);
    };



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


    Passport.js file



    passport.use('local-signup', new LocalStrategy({
    // by default, local strategy uses username and password, we will override with email
    usernameField : 'email',
    passwordField : 'password',
    passReqToCallback : true },


    function(req, password, email, done) {
    //specify new variables (As well as password & email already captured in function)
    var fname = req.body.fname;
    var lname = req.body.lname;
    var role = req.body.role;


    User.findOne({ 'local.email' : email }, function(err, user, req) {
    // if there are any errors, return the error
    if (err)
    return done(err);

    // check to see if theres already a user with that email
    if (user) {
    return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
    } else {

    // if there is no user with that email
    // create the user
    var newUser = new User();

    // set the user's local credentials
    newUser.local.email = email;
    newUser.local.password = newUser.generateHash(password);
    newUser.local.fname = fname;
    newUser.local.lname = lname;
    newUser.local.role = role;
    // save the user
    newUser.save(function(err) {
    if (err)
    throw err;
    return done(null, newUser);
    });
    }
    });
    }));


    Routes.js file



     app.post('/signup',

    check('email')
    .not().isEmpty().withMessage('Please specify an email.')
    .isEmail().withMessage('Incorrect email format.'),
    check('password')
    .not().isEmpty().withMessage('Please specify a password.')
    .matches(/^(?=.*d)(?=.*[a-z])(?=.*[A-Z])(?!.* )(?=.*[^a-zA-Z0-9]).{8,}$/, 'i').withMessage('Password must include 1 uppercase character, 1 number and 1 special character')
    .isLength({min: 8, max: 100}).withMessage('Password must be at least 8 characters in length.'),
    check('fname')
    .not().isEmpty().withMessage('Please enter your first name.'),
    check('lname')
    .not().isEmpty().withMessage('Please enter your last name.'),
    check('role')
    .not().isEmpty().withMessage('Please state your role.'),

    function(req, res, next) {
    var errors = validationResult(req);
    if (!errors.isEmpty()) {
    return res.render('signup.html', {message: errors.array()[0].msg});
    } else {

    passport.authenticate('local-signup', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/signup'); }
    req.logIn(user, function(err) {
    if (err) { return next(err); }
    return res.redirect('/profile');
    });
    })(req, res, next);
    };
    });









    share|improve this question



























      0












      0








      0







      I've been racking my brain over this for hours :-/



      I'm trying to incorporate Express Validator checks before Passport authenticate in order for a new user to signup/register.



      From reading online and a ton of tutorials I understand Passport needs to be used as custom callback (http://www.passportjs.org/docs/authenticate/) if valdidate checks are to be used first. However I've tried many different options and either the checks work and passport authenticates with no new user added to the mongodb database, or I can register a new user email despite that user email already existing.



      Any help is much appreciated! Please let me know if you need more code/info from me. Thanks in advance!



      User.js file



      var mongoose = require('mongoose');
      var bcrypt = require('bcrypt-nodejs');
      var userSchema = mongoose.Schema({

      local : {
      email : String,
      password : String,
      fname : String,
      lname : String,
      role : String,
      }

      });

      // generating a hash =============
      userSchema.methods.generateHash = function(password) {
      return bcrypt.hashSync(password, bcrypt.genSaltSync(12), null);
      };

      // checking if password is valid
      userSchema.methods.validPassword = function(password) {
      return bcrypt.compareSync(password, this.local.password);
      };



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


      Passport.js file



      passport.use('local-signup', new LocalStrategy({
      // by default, local strategy uses username and password, we will override with email
      usernameField : 'email',
      passwordField : 'password',
      passReqToCallback : true },


      function(req, password, email, done) {
      //specify new variables (As well as password & email already captured in function)
      var fname = req.body.fname;
      var lname = req.body.lname;
      var role = req.body.role;


      User.findOne({ 'local.email' : email }, function(err, user, req) {
      // if there are any errors, return the error
      if (err)
      return done(err);

      // check to see if theres already a user with that email
      if (user) {
      return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
      } else {

      // if there is no user with that email
      // create the user
      var newUser = new User();

      // set the user's local credentials
      newUser.local.email = email;
      newUser.local.password = newUser.generateHash(password);
      newUser.local.fname = fname;
      newUser.local.lname = lname;
      newUser.local.role = role;
      // save the user
      newUser.save(function(err) {
      if (err)
      throw err;
      return done(null, newUser);
      });
      }
      });
      }));


      Routes.js file



       app.post('/signup',

      check('email')
      .not().isEmpty().withMessage('Please specify an email.')
      .isEmail().withMessage('Incorrect email format.'),
      check('password')
      .not().isEmpty().withMessage('Please specify a password.')
      .matches(/^(?=.*d)(?=.*[a-z])(?=.*[A-Z])(?!.* )(?=.*[^a-zA-Z0-9]).{8,}$/, 'i').withMessage('Password must include 1 uppercase character, 1 number and 1 special character')
      .isLength({min: 8, max: 100}).withMessage('Password must be at least 8 characters in length.'),
      check('fname')
      .not().isEmpty().withMessage('Please enter your first name.'),
      check('lname')
      .not().isEmpty().withMessage('Please enter your last name.'),
      check('role')
      .not().isEmpty().withMessage('Please state your role.'),

      function(req, res, next) {
      var errors = validationResult(req);
      if (!errors.isEmpty()) {
      return res.render('signup.html', {message: errors.array()[0].msg});
      } else {

      passport.authenticate('local-signup', function(err, user, info) {
      if (err) { return next(err); }
      if (!user) { return res.redirect('/signup'); }
      req.logIn(user, function(err) {
      if (err) { return next(err); }
      return res.redirect('/profile');
      });
      })(req, res, next);
      };
      });









      share|improve this question















      I've been racking my brain over this for hours :-/



      I'm trying to incorporate Express Validator checks before Passport authenticate in order for a new user to signup/register.



      From reading online and a ton of tutorials I understand Passport needs to be used as custom callback (http://www.passportjs.org/docs/authenticate/) if valdidate checks are to be used first. However I've tried many different options and either the checks work and passport authenticates with no new user added to the mongodb database, or I can register a new user email despite that user email already existing.



      Any help is much appreciated! Please let me know if you need more code/info from me. Thanks in advance!



      User.js file



      var mongoose = require('mongoose');
      var bcrypt = require('bcrypt-nodejs');
      var userSchema = mongoose.Schema({

      local : {
      email : String,
      password : String,
      fname : String,
      lname : String,
      role : String,
      }

      });

      // generating a hash =============
      userSchema.methods.generateHash = function(password) {
      return bcrypt.hashSync(password, bcrypt.genSaltSync(12), null);
      };

      // checking if password is valid
      userSchema.methods.validPassword = function(password) {
      return bcrypt.compareSync(password, this.local.password);
      };



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


      Passport.js file



      passport.use('local-signup', new LocalStrategy({
      // by default, local strategy uses username and password, we will override with email
      usernameField : 'email',
      passwordField : 'password',
      passReqToCallback : true },


      function(req, password, email, done) {
      //specify new variables (As well as password & email already captured in function)
      var fname = req.body.fname;
      var lname = req.body.lname;
      var role = req.body.role;


      User.findOne({ 'local.email' : email }, function(err, user, req) {
      // if there are any errors, return the error
      if (err)
      return done(err);

      // check to see if theres already a user with that email
      if (user) {
      return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
      } else {

      // if there is no user with that email
      // create the user
      var newUser = new User();

      // set the user's local credentials
      newUser.local.email = email;
      newUser.local.password = newUser.generateHash(password);
      newUser.local.fname = fname;
      newUser.local.lname = lname;
      newUser.local.role = role;
      // save the user
      newUser.save(function(err) {
      if (err)
      throw err;
      return done(null, newUser);
      });
      }
      });
      }));


      Routes.js file



       app.post('/signup',

      check('email')
      .not().isEmpty().withMessage('Please specify an email.')
      .isEmail().withMessage('Incorrect email format.'),
      check('password')
      .not().isEmpty().withMessage('Please specify a password.')
      .matches(/^(?=.*d)(?=.*[a-z])(?=.*[A-Z])(?!.* )(?=.*[^a-zA-Z0-9]).{8,}$/, 'i').withMessage('Password must include 1 uppercase character, 1 number and 1 special character')
      .isLength({min: 8, max: 100}).withMessage('Password must be at least 8 characters in length.'),
      check('fname')
      .not().isEmpty().withMessage('Please enter your first name.'),
      check('lname')
      .not().isEmpty().withMessage('Please enter your last name.'),
      check('role')
      .not().isEmpty().withMessage('Please state your role.'),

      function(req, res, next) {
      var errors = validationResult(req);
      if (!errors.isEmpty()) {
      return res.render('signup.html', {message: errors.array()[0].msg});
      } else {

      passport.authenticate('local-signup', function(err, user, info) {
      if (err) { return next(err); }
      if (!user) { return res.redirect('/signup'); }
      req.logIn(user, function(err) {
      if (err) { return next(err); }
      return res.redirect('/profile');
      });
      })(req, res, next);
      };
      });






      node.js express authentication passport.js






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 13 '18 at 11:26

























      asked Nov 12 '18 at 21:29









      SamG

      12




      12





























          active

          oldest

          votes











          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%2f53270383%2fpassport-js-as-custom-callback-with-express-validator-cant-save-new-user-to%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          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.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • 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%2f53270383%2fpassport-js-as-custom-callback-with-express-validator-cant-save-new-user-to%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

          Bressuire

          Vorschmack

          Quarantine