0

I'm trying to build a todo app where It has a signup and sign in page for which I'm trying to hash the password and compare the same when a user tries to login. Initially with bcrypt sync method I was able to hash the password however my Scompare function always returned false .Then I have changed it async method and I see that it's not getting hashed and even compare function is also not working .Can someone helpme with this?

databases/sqlite.js:

const Sequelize = require('sequelize');
const bcrypt = require('bcrypt');
const saltRounds = 10;
const sequelize = new Sequelize({
    dialect: "sqlite",
    storage: path.join(__dirname,"database.sqlite")
});
const User= sequelize.define("users", {
     name: {
         type: Sequelize.STRING,
      },
      email: {
        type: Sequelize.STRING,
        unique: true,
      },
      password: {
        type: Sequelize.STRING,
      }},

    {
        hooks: {
          beforeCreate: (user) => {
            /*const salt = bcrypt.genSaltSync();
            user.password = bcrypt.hashSync(user.password, 
salt);*/

bcrypt.hash(user.password, saltRounds, function(err, hash) {
              // Store hash in your password DB.
              if(err) console.log("something wrong with hashing",err)
              user.password=hash;
          });

          }
        },
        instanceMethods: {
          validPassword:  function(password) {
           
          
              bcrypt.compare(password, user.password, function(err, result) {
                  if (err) { throw (err); }
                  console.log(result);
                  return result;
              });
          }
            //return bcrypt.compareSync(password, this.password);
          }
          
    });
    sequelize
      .sync()
      .then(() =>
        console.log(
          "users table has been successfully created, if one doesn't exist"
        )
      )
      .catch(error => console.log("This error occurred"));
Alex Yepes
  • 1,160
  • 1
  • 9
  • 21
  • 1
    Does this answer your question? [Sequelize create model with beforeCreate hook](https://stackoverflow.com/questions/31427566/sequelize-create-model-with-beforecreate-hook) – ggorlen Nov 03 '20 at 20:22
  • As per the link provided above I' m returning a promise now and it's getting hashed but however Even if I enter the credentials correctly the compare function resulting false @ggorlen – priyatham ik Nov 03 '20 at 21:39
  • Whoever got stuck at this point please make a not that instance methods needs to be declared using classes like User.prototype.validPassword if you are using express>4.0 which fixed my error, FYI. – priyatham ik Nov 05 '20 at 09:01
  • Glad it worked out. You can post a [self-answer](https://stackoverflow.com/help/self-answer). – ggorlen Nov 05 '20 at 13:43

0 Answers0