Search code examples
node.jsexpressmongoosebcrypt

Bcrypt not hashing and salting passwords anymore


In a previous version of my current app I have a working backend app with bcrypt who salts and hashes my passwords. In this version I now work on is a 1 on 1 copy with the same routes, controllers. All works perfectly fine, the data from the post request is nice saved but without a hashed password. The blank password is now showing.

I work on windows 10, 64 bit, both versions in my versions are bcrypt are 3.0.4 local installed. I work with mongoDB and mongoose.

I use the most general version of code for hashing and salting. As said, this still works in my elder version.

Anybody has a clue what has changed?

Here the code:

//relevant parts of app.js
const express = require('express');
const path = require('path');
//const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const helmet = require('helmet');
const cors = require('cors');

// connection to mongoose 
require('./app_api/models/db');

//route to routes
const users = require('./app_api/routes/users');

//routes (post request)
router
	.route('/user/signup')
	.post(AuthenticationControllerPolicy.signupPost, ctrlUsers.signupPost); 

//fragment of the post controller
const signupPost = function (req, res) {
	//Make sure this account already exists
	Base.
		findOne({
			userName: req.body.userName
		}, function (user, err) {
			//Make sure user doesn 't already exist
			if (err) {
				return res.status(400).send({ msg: 'The email address you have entered is already associated with another account.' });
			} else { //etc..


//Create and save the user
user = new Base({
password: req.body.password
});
user.save(function (err) {

// base model with hashing and salting code
const baseSchema = new mongoose.Schema({
	password: { type: String, required: true }
	}, options);

const Base = mongoose.model('Base', baseSchema);

// salting and hashing
						

// hashing and salting before saving
baseSchema.pre('save', function (next) {

	let base = this;
	// only hash the password if it has been modified (or is new)
	if (!base.isModified('password')) return next();

	//generate a salt
	bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
	if (err) return next(err);

	// hash the password using our new salt
	bcrypt.hash(base.password, salt, function (err, hash) {
	if (err) return next(err);

	// override the cleartext password with the hashed one
	base.password = hash;
	next();
		});
	});
	});


Solution

  • Try something like this. make sure const Base = mongoose.model('Base', baseSchema); is at the end of the code since it is responsible of creating the model and since you have declared it on the top before the pre hook it will not be created and the password will not be hashed.

        // On Save Hook, encrypt password
        // Before saving a model, run this function
        baseSchema.pre('save', function (next) {
          //get access to the user model
          const base= this;
    
          // generate a salt then run callback
          bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
            if (err) { return next(err); }
    
            // hash (encrypt) our password using the sale
            bcrypt.hash(base.password, salt, null, function (err, hash) {
              if (err) { return next(err); }
    
              //overwrite plain text password with encrypted password
              base.password = hash;
              next();
            });
          });
        });
    
    const Base = mongoose.model('Base', baseSchema);