handsome
handsome

Reputation: 2402

how to encrypt passwords with beforeBulkCreate hook in sequelize

I´m trying to encrypt password before bulk create with sequelize.

const bcrypt = require('bcryptjs');

module.exports = (sequelize, DataTypes) => {
    const User = sequelize.define('users', {
        username: {
            type: DataTypes.STRING,
            allowNull: false,
            required: true
        },
        password: {
            type: DataTypes.STRING,
            allowNull: false,
            required: true
        },
    },
    {
        freezeTableName: true,
        hooks: {
            beforeBulkCreate: function(records) {

                records.forEach((user, index) => {
                    return bcrypt.hash(user.password, 10)
                        .then(hash => {
                            user.password = hash;
                            console.log('password hash:', user.password);
                        })
                        .catch(err => { 
                            throw new Error(); 
                        });     
                })
            },
            beforeCreate: (user) => {
                return bcrypt.hash(user.password, 10)
                    .then(hash => {
                        user.password = hash;
                    })
                    .catch(err => { 
                        throw new Error(); 
                    });
            }
        }
    });

    User.prototype.validPassword = (password) => {

        return bcrypt.compareSync(password, this.password);
    };

    return User;
}

hooks is called but the password that´s store in the database is the plain one not the new one

const userData = [
    { username: 'John', password: '123' },
    { username: 'Mary', password: '321' },
];

User.bulkCreate(userData, { returning: true })
    .then((result) => {
        console.log('User data success');
    })
    .catch((error) => {
        console.log(error);
    });

I also tried passing the { individualHooks: true } option but doing this records are not being inserted at all.

Upvotes: 1

Views: 1226

Answers (1)

BrondChux
BrondChux

Reputation: 11

I came here in search of an answer to this ~ 3 years old question. Chances are that >= 3 years later someone else will come looking for the same.

Here, I solved mine using bcrypt.hashSync()

I know they recommend using the asynchronous bcrypt.hash() solution but sometimes most optimal isn't always the solution.

You can learn more here bcrypt npm docs

hooks: {
        beforeBulkCreate: (users) => {
            users.forEach((user) => {
                // to see the properties added by sequelize
                console.table(user);

                // now modify the "dataValues" property
                user.dataValues.password = bcrypt.hashSync(user.password, 10);
            });
        },
        // other hooks here
    },

Upvotes: 1

Related Questions