Using BCrypt with Sequelize Model

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;
}

Bcrypt Is no longer part of node, so I included example with new module of crypto

I am sharing this code from one of working project.

My config file

require('dotenv').config();
const { Sequelize,DataTypes ,Model} = require("sequelize");
module.exports.Model = Model;
module.exports.DataTypes = DataTypes;
module.exports.sequelize  = new Sequelize(process.env.DB_NAME,process.env.DB_USER_NAME, process.env.DB_PASSWORD, {
 host: process.env.DB_HOST,
 dialect: process.env.DB_DISELECT,
 pool: {
   max: 1,
   min: 0,
   idle: 10000
 },
 //logging: true
});

My user model

const { sequelize, DataTypes, Model } = require('../config/db.config');
  var crypto = require('crypto');
  class USERS extends Model {
    validPassword(password) {
      var hash = crypto.pbkdf2Sync(password,
        this.SALT, 1000, 64, `sha512`).toString(`hex`);
      console.log(hash == this.PASSWORD)
      return this.PASSWORD === hash;
    }
  }
  USERS.init(
    {
      ID: {
        autoIncrement: true,
        type: DataTypes.BIGINT,
        allowNull: false,
        primaryKey: true
      },
      MOBILE_NO: {
        type: DataTypes.BIGINT,
        allowNull: false,
        unique: true
      },
      PASSWORD: {
        type: DataTypes.STRING(200),
        allowNull: false
      },
      SALT: {
        type: DataTypes.STRING(200),
        allowNull: false
      }
    },

    {
      sequelize,
      tableName: 'USERS',
      timestamps: true,
      hooks: {
        beforeCreate: (user) => {
          console.log(user);
          user.SALT = crypto.randomBytes(16).toString('hex');
          user.PASSWORD = crypto.pbkdf2Sync(user.PASSWORD, user.SALT,
            1000, 64, `sha512`).toString(`hex`);
        },
      }
    });


  module.exports.USERS = USERS;

And Auth Controller

const { USERS } = require('../../../models/USERS');
module.exports = class authController {
    static register(req, res) {

        USERS.create({
            MOBILE_NO: req.body.mobile,
            PASSWORD: req.body.password,
            SALT:""
        }).then(function (data) {
            res.json(data.toJSON());
        }).catch((err) => {
            res.json({
                error: err.errors[0].message
            })
        })
    }
    static login(req, res) {
        var message = [];
        var success = false;
        var status = 404;
        USERS.findOne({
           where:{
            MOBILE_NO: req.body.mobile
           }
        }).then(function (user) {
            if (user) {
                message.push("user found");
                if(user.validPassword(req.body.password)) {
                    status=200;
                    success = true
                    message.push("You are authorised");
                }else{
                    message.push("Check Credentials");
                }
            }else{
                message.push("Check Credentials");
            }
           
            res.json({status,success,message});
        });
    }
}

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');
    }
});

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(); 
        });
});