Sunday, 14 May 2017

get valid password with bcrypt

I am using nodejs with sequelize to setup my database, and currently i am trying to hash and salt my password, the hashing i already did, but now when i tyr to login i want to compare the password send in req.body with the hashed one, so i did this:

router.post('/', function (req, res, next) {
  console.log("hi");
  if (JSON.stringify(req.body) == "{}") {
    return res.status(400).json({ Error: "Login request body is empty" });
  }
  if (!req.body.username || !req.body.password) {
    return res.status(400).json({ Error: "Missing fields for login" });
  }

    var password = User.validPassword(req.body.password);


  // search a user to login
  User.findOne({ where: { username: req.body.username, password: password } }) // searching a user with the same username and password sended in req.body
    .then(function (user) {
      if (!user) {
        return res.status(400).json({ Error: "There is no user with those fields" }); // if there is no user with specific fields send
      }
        return res.status(400).json({ Error: "loged in!" }); // username and password match
    }).catch(function (err) {
      return res.status(200).json({ message: "server issues when trying to login!" }); // server problems
    });
});

my model is like this:

"use strict";
var sequelize = require('./index');
var bcrypt = require('bcrypt-nodejs');

module.exports = function (sequelize, DataTypes) {
  var User = sequelize.define("User", {
    username: DataTypes.STRING,
    email: DataTypes.STRING,
    password: DataTypes.STRING
  }, {
      classMethods: {
        generateHash: function (password) {
          console.log("hi");
          return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
        },
        validPassword: function (password) {
          return bcrypt.compareSync(password, this.password);
        }
      }

    });



  return User;
}

i don't get any response from

var password = User.validPassword(req.body.password);

i tried to console.log but stilm no response, when i try to go to router /login it just doesn0t give me any response it is loading all the time, any sugestion?



via Antonio Costa

No comments:

Post a Comment