I'm working on my first Sequelize server and mySQL db. I can't seem to get bcrypt to work and hash my users passwords. I can get the model to successfully add to the db. But none of the methods for password encrypting seem to be working.
Here is my users model:
module.exports = function(sequelize, DataTypes) {
const bcrypt = require('bcrypt');
const Users = sequelize.define('users', {
user_id: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4
},
..................
user_password: {
type: DataTypes.STRING,
validate: {
// must have at least 6 characters no more than 16
// must contain at least 1 capital and 1 number
is: /^(?=.*\d)(?=.*[A-Z])(?!.*[^a-zA-Z0-9@#$^+=])(.{6,16})$/
// must not be ['password', 'username', etc...]
}
}
}, {
freezeTableName: true,
})
Users.beforeCreate(function(user, options) {
return cryptPassword(user.user_password)
.then(success => {
user.user_password = success;
})
.catch(err => {
if (err) console.log(err);
});
});
function cryptPassword(password) {
console.log("cryptPassword " + password);
return new Promise(function(resolve, reject) {
bcrypt.genSalt(10, function(err, salt) {
// Encrypt password using bycrpt module
if (err) return reject(err);
bcrypt.hash(password, salt, null, function(err, hash) {
if (err) return reject(err);
return resolve(hash);
});
});
});
// Users.associate = function(models) {
// Users.hasMany(models.comments, {foreignKey: "comment_id"})
// Users.hasMany(models.posts, {foreignKey: "post_id"})
}
return Users
};
Any help is appreciated, thanks!