简体   繁体   中英

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?

To start with, your route defines a post action to / not /login . You can use postman to try that out if you don't have a front-end yet.

The validPassword method should be called on an instance of the User model so you should have written this portion of the code like 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" });
  }

  // search a user to login
  User.findOne({ where: { username: req.body.username } }) // searching a user with the same username and password sended in req.body
    .then(function (user) {
      if(user && user.validPassword(req.body.password)) {
         return res.status(200).json({message: "login successful"});
      } else {
         return res.status(401).json({message: "Unauthorized"});
      }

    }).catch(function (err) {
      return res.status(200).json({ message: "server issues when trying to login!" }); // server problems
    });
});

Also in you catch method, the status code should be something that depicts internal server error like 500 . 200 is inappropriate.

Soo seems like I could answer my own question, with the help of Femi Oladeji, basicly the problem was related to the fact that i want to acess the methods trough a instance and not a model.

So when I tried to acces it with the user instance, there was no method that treat instances, so made some changes on my model.

"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) {
          return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
        },

      },
      instanceMethods: {
        validPassword: function (password) {
          console.log(password, this.password)
          return bcrypt.compareSync(password, this.password);
        }
      }


    });



  return User;
}

and there is the instanceMethods, that can treat the instance :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM