0

I would like to hash user password at the creation of a user. The user is created, but the password is not hashed I don't understand why .. here is my code :

var mongoose = require('mongoose');
var jwt = require('jsonwebtoken');
var User = mongoose.model('User');
var config = require('../../config/config');
var bcrypt = require('bcrypt');
var SALT_WORK_FACTOR = 10;

exports.create_a_user = function(req, res) {
    var user = new User(req.body);
user.schema.pre('save', function(next){
var user = this;
if (!user.isModified('password')) return next();

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

    bcrypt.hash(user.password, salt, function(err, hash){
        if(err) return next(err);

        user.password = hash;
        next();
    });
  });
});


 user.save(function(err, user) {
        if (err){
            res.send(err);
        }
        res.json(user);
    });
};

Here my user model :

module.exports = mongoose.model('User', new Schema({
    lastname: {
       type: String,
       validate: {
         validator: function(v) {
           return /^([a-zA-ZàáâäæçéèêëîïôœùûüÿÀÂÄÆÇÉÈÊËÎÏÔŒÙÛÜŸ \-\']+)$/.test(v);
         },
         message: 'Le champ {PATH} ne doit pas contenir de caractères spéciaux ou de chiffres !'
       },
       required: [true, "Le champ nom de famille est requis"]
     },

    firstname: {
       type: String,
       validate: {
         validator: function(v) {
           return /^([a-zA-ZàáâäæçéèêëîïôœùûüÿÀÂÄÆÇÉÈÊËÎÏÔŒÙÛÜŸ \-\']+)$/.test(v);
         },
         message: 'Le champ {PATH} ne doit pas contenir de caractères spéciaux ou de chiffres !'
       },
       required: [true, "Le champ prénom est requis"]
     },

    mail: {
       type: String,
       validate: {
         validator: function(v) {
           return /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/.test(v);
         },
         message: '{VALUE} n\'est pas une adresse mail valide!'
       },
       required: [true, "L'email est requis"]
     },

    password: {
       type: String,
       required: [true, "Le mot de passe est requis"]
     },

    phone: {
        type: String,
        validate: {
          validator: function(v) {
            return /^0[0-9]([-. ]?\d{2}){4}[-. ]?$/.test(v);
          },
          message: '{VALUE} n\'est pas un numéro de téléphone valide!'
        },
        required: [true, 'Le numéro de téléphone est requis']
      },

}));

And my form :

<form method="post" action="/api/v1/user/register">
    <input type="text" name="lastname" placeholder="lastname"><br>
    <input type="text" name="firstname" placeholder="firstname"><br>
    <input type="text" name="adress" placeholder="adress"><br>
    <input type="text" name="mail" placeholder="mail"><br>
    <input type="password" name="password" placeholder="password"><br>
    <input type="text" name="phone" placeholder="phone"><br>
    <input type="date" name="birthdate" placeholder="birthdate"><br>
    <input type="submit" value="Connection">

I've been through a lot of different sites, the method is always the same. Also, it doesn't recognize ".pre()" function without .schema before and then the create user works but without any hash password. Does anybody have any ideas ?

0

1 Answer 1

1

You should set up your pre save hook on your schema before you export your model.

User model:

var UserSchema = new Schema({
  ...
})

UserSchema.pre('save', function(next) {

  var user = this

  if (!user.isModified('password')) return next()

  bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {

    if (err) return next(err)

    bcrypt.hash(user.password, salt, function(err, hash) {

      if(err) return next(err)

      user.password = hash

      next()

    })

  })

})

module.exports = mongoose.model('User', UserSchema)
Sign up to request clarification or add additional context in comments.

2 Comments

Thx for your answer, when I do that it says : User is not defined
Try importing your model like this: var User = require(‘./path/to/model/User’)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.