简体   繁体   中英

Password bcrypt return undefined

I'm trying to encrypt a password with bcrypt but when I call the this.setDataValue('password',hash) the return becomes undefined and doesn't save because of ValidationError (not null), but in the console.log in the line above it's hashed. I tried changing the es6 arrow function for function () instead, but as expected I don't have access to the this.setDataValue . Can anybody give me a light?

const { Sequelize } = require('sequelize');
const {database,username,password,host } = require('./dbcon');
const bcrypt = require('bcrypt');
const saltRounds = 10;

const sequelize = new Sequelize(database , username, password, {host:host ,dialect: 'mariadb'});

const user = sequelize.define('users',{
    mail:{
        type:Sequelize.STRING,
        allowNull:false
    },
    firstName:{
        type:Sequelize.STRING,
        allowNull:false,
    },
    lastName:{
        type:Sequelize.STRING,
        allowNull:false,
    },
    password:{
        type:Sequelize.STRING,
        allowNull:false,
        set(value) {
            bcrypt.hash(value,saltRounds).then(f(hash)=>{
                console.log(value,hash);
                this.setDataValue('password',hash);
            });

        }
    },
    username:{
        type:Sequelize.STRING,
        allowNull:false,
    }

})

try {
    sequelize.authenticate().then(res =>{
        console.log('Connection has been established successfully.');
        user.sync({ force: true });
    });

} catch (error) {
    console.error('Unable to connect to the database:', error);
}

module.exports = {sequelize,user};

You can use beforeCreate hook and bcrypt async method or instanceMethods in options:

const user = sequelize.define('users',{
        mail:{
            type:Sequelize.STRING,
            allowNull:false
        },
        firstName:{
            type:Sequelize.STRING,
            allowNull:false,
        },
        lastName:{
            type:Sequelize.STRING,
            allowNull:false,
        },
        password:{
            type:Sequelize.STRING,
            allowNull:false
        },
        username:{
            type:Sequelize.STRING,
            allowNull:false,
        }
    }, {
        instanceMethods: {
            generateHash(password) {
                return bcrypt.hash(password, bcrypt.genSaltSync(8));
            }
        }
    }

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM