Using BCrypt with Sequelize Model

帅比萌擦擦* 提交于 2019-12-17 16:09:26

问题


I'm trying to use the bcrypt-nodejs package with my sequelize model and was tring to follow a tutorial to incorporate the hashing into my model, but I'm getting an error at generateHash. I can't seem to figure out the issue. Is there a better way to incorporate bcrypt?

Error:

/Users/user/Desktop/Projects/node/app/app/models/user.js:26
User.methods.generateHash = function(password) {
                          ^
TypeError: Cannot set property 'generateHash' of undefined
    at module.exports (/Users/user/Desktop/Projects/node/app/app/models/user.js:26:27)
    at Sequelize.import (/Users/user/Desktop/Projects/node/app/node_modules/sequelize/lib/sequelize.js:641:30)

model:

var bcrypt = require("bcrypt-nodejs");

module.exports = function(sequelize, DataTypes) {

var User = sequelize.define('users', {
    annotation_id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    firstName: {
        type: DataTypes.DATE,
        field: 'first_name'
    },
    lastName: {
        type: DataTypes.DATE,
        field: 'last_name'
    },
    email: DataTypes.STRING,
    password: DataTypes.STRING,

}, {
    freezeTableName: true
});

User.methods.generateHash = function(password) {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};

User.methods.validPassword = function(password) {
    return bcrypt.compareSync(password, this.local.password);
};
    return User;
}

回答1:


Methods should be provided in the "options" argument of sequelize.define

const bcrypt = require("bcrypt");

module.exports = function(sequelize, DataTypes) {
    const User = sequelize.define('users', {
        annotation_id: {
            type: DataTypes.INTEGER,
            autoIncrement: true,
            primaryKey: true
        },
        firstName: {
            type: DataTypes.DATE,
            field: 'first_name'
        },
        lastName: {
            type: DataTypes.DATE,
            field: 'last_name'
        },
        email: DataTypes.STRING,
        password: DataTypes.STRING
    }, {
        freezeTableName: true,
        instanceMethods: {
            generateHash(password) {
                return bcrypt.hash(password, bcrypt.genSaltSync(8));
            },
            validPassword(password) {
                return bcrypt.compare(password, this.password);
            }
        }
    });

    return User;
}



回答2:


Other alternative: Use hook and bcrypt async mode

User.beforeCreate((user, options) => {

    return bcrypt.hash(user.password, 10)
        .then(hash => {
            user.password = hash;
        })
        .catch(err => { 
            throw new Error(); 
        });
});



回答3:


There's a tutorial out there on how to get a sequelize/postgreSQL auth system working with hooks and bcrypt.

The guy who wrote the tutorial did not use async hash/salt methods; in the user creation/instance method section he used the following code:

hooks: {
  beforeCreate: (user) => {
    const salt = bcrypt.genSaltSync();
    user.password = bcrypt.hashSync(user.password, salt);
  }
},
instanceMethods: {
  validPassword: function(password) {
    return bcrypt.compareSync(password, this.password);
  }
}    

Newer versions of Sequelize don't like instance methods being declared this way - and multiple people have explained how to remedy this (including someone who posted on the original tutorial):

The original comment still used the synchronous methods:

User.prototype.validPassword = function (password) {
    return bcrypt.compareSync(password, this.password);
};

All you need to do to make these functions asyncronous is this:

Async beforeCreate bcrypt genSalt and genHash functions:

beforeCreate: async function(user) {
    const salt = await bcrypt.genSalt(10); //whatever number you want
    user.password = await bcrypt.hash(user.password, salt);
}

User.prototype.validPassword = async function(password) {
    return await bcrypt.compare(password, this.password);
}

On the node.js app in the login route where you check the password, there's a findOne section:

User.findOne({ where: { username: username } }).then(function (user) {
    if (!user) {
        res.redirect('/login');
    } else if (!user.validPassword(password)) {
        res.redirect('/login');
    } else {
        req.session.user = user.dataValues;
        res.redirect('/dashboard');
    }
});

All you have to do here is add the words async and await as well:

User.findOne({ where: { username: username } }).then(async function (user) {
    if (!user) {
        res.redirect('/login');
    } else if (!await user.validPassword(password)) {
        res.redirect('/login');
    } else {
        req.session.user = user.dataValues;
        res.redirect('/dashboard');
    }
});


来源:https://stackoverflow.com/questions/34120548/using-bcrypt-with-sequelize-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!