hidace hidace - 3 months ago 85
Javascript Question

How to immediately save within a Sequelize beforeCreate hook?

I'm trying to hash a password before it's created and saved. However, when I have my hooked defined as below, I noticed that the log creates a guest instance with the original password and then immediately updates it. I'm not sure why.

// define model

const Guest = sequelize.define('guest', {
email: {
type: Sequelize.STRING,
allowNull: false,
},
password: {
type: Sequelize.STRING,
allowNull: false,
}
});

Guest.beforeCreate(function(guest) {
bcrypt.genSalt(10, function(error, salt) {
if (error) { return error }
bcrypt.hash(guest.password, salt, null, function(error, hash) {
if (error) { return error }
guest.password = hash;
guest.save();
})
})
});


Here's where I actually create an instance in another file

//..

const email = req.body.email;
const password = req.body.password;

Guest.findOne({ where: { email: email }})
.then(function(existingUser) {

if (existingUser) {
return res.status(422).send({ error: 'Email is already in use'})
}

Guest.create({
email: email,
password: password
}).then(function(guest) {
res.json({ token: tokenForGuest(guest) });
});

});


However, when I do this, it creates the instance with this password immediately (not creating with the provided password and then updating with that I've set):

Guest.beforeCreate(function(guest) {
guest.password = 'TEST';
});


Here's my server log that I'm getting:

Executing (default): SELECT "id", "email", "password", "createdAt", "updatedAt"
FROM "guests" AS "guest" WHERE "guest"."email" = 'mytestemail@example.com' LIMIT
1;

Executing (default): INSERT INTO "guests"
("id","email","password","createdAt","updatedAt") VALUES
(DEFAULT,'mytestemail@example.com','passwordsecret123','2016-06-26 16:26:54.683
+00:00','2016-06-26 16:26:54.683 +00:00') RETURNING *;
::1 - - [26/Jun/2016:16:26:55 +0000] "POST /signup HTTP/1.1" 200 133 "-"
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like
Gecko) Postman/4.2.2 Chrome/47.0.2526.73 Electron/0.36.2 Safari/537.36"

Executing (default): UPDATE "guests" SET
"password"='$2a$10$VsU97hLMxZ76zGmNfJVlfOeXayyFbGMKK/EwE3SvKhOOEi9oAm9Qy',"updated
At"='2016-06-26 16:26:55.428 +00:00' WHERE "id" = 20


Any and all help would be greatly appreciated. Thanks!

Answer

try

Guest.beforeCreate(function(guest, options, done) {
    bcrypt.genSalt(10, function(err, salt) {
        if (err) return done(err);
        console.log('Salt: ' + 'getting ' + salt);
        bcrypt.hash(guest.password, salt, null, function(err, hash) {
            if (err) return done(err);

            console.log('Info: ' + 'getting ' + hash);

            guest.password = hash;

            console.log('Info: ' + 'password now is: ' + guest.password);

            return done(null,guest);
        });
    });
});