Node.js中的密码哈希

时间:2018-12-14 10:44:47

标签: javascript node.js

我是StackOverflow和开发领域的新手。目前正在学习JS和Node,我正在开发一个个人项目,这将是一个任务管理Web应用程序。我在DB中编写了用于用户数据插入/检查的注册/身份验证控制器(使用MySQL),但是ATM我将密码保存为纯文本格式。我想对密码进行哈希处理并将其保存在数据库中,但是当我查看表时,传递的值将另存为“对象承诺”,因此我认为它当前未进行哈希处理。如何正确保存注册中的值并在auth中对其进行验证?下面是身份验证和注册控制器的代码。谢谢。

注册控制器:

var mysqlConnection = require ('../config');
const bcrypt = require ('bcrypt');
const saltRounds = 10;
module.exports.register=function(req,res){
  var today = new Date();
  var users={
      "firstname":req.body.firstname,
      "lastname" : req.body.lastname,
      "email":req.body.email,
      "password":bcrypt.hash(req.body.password, saltRounds),
      "signup_date":today,
      "last_login_date":today
  }

  mysqlConnection.query('SELECT count(email) as count FROM users where email = "' + req.body.email + '"', function (error, results) {
    console.log(error, results[0].email);
  }) 
  mysqlConnection.query('INSERT INTO users SET ?',users, function (error, results, fields) {
    console.log(error, results);
    if (error) {
      res.json(
          error
      )
    }else{
        console.log('User registered succesfully.');
        res.redirect('/');
    }
  });
}

这是auth-controller:

var mysqlConnection = require ('../config');
const bcrypt = require ('bcrypt');

module.exports.auth = function (req, res, next) {
  var email = req.body.email 
  var password = req.body.password
  console.log(email, password);
  mysqlConnection.query('SELECT password FROM users where email = "' + email + '"', function (error, results) {
    console.log(error, results[0]);
    if (error) {
        res.error = error;
    }else{
      if(results.length >0){
        bcrypt.compare(password,results[0].password, function (err,res){
          if(password === results[0].password){
              console.log('User logged in succesfully.');
              res.error = error;
              res.user = results[0];
              res.redirect('/');
          }else{
              res.error = error;
              res.user = null;
        }
      }
        )}
      else{
        res.error = error;
        res.user = null;
        res.redirect('/register');
      }
    }
    next();
  });
} 

0 个答案:

没有答案