我是 StackOverflow 和开发世界的新手。目前正在学习 JS 和 node,我正在开发一个个人项目,该项目将是一个任务管理 Web 应用程序。我为 DB 中的用户数据插入/检查编写了 register/auth 控制器(使用 MySQL),但 ATM 我以纯文本格式保存密码。我想对密码进行哈希处理并将其保存在数据库中,但是当我查看表时,传递的值被保存为“对象承诺”,所以我认为它目前不是哈希处理。如何正确保存注册中的值并在身份验证中验证它?下面是 auth 和 register 控制器的代码。谢谢。
寄存器控制器:
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('/');
}
});
}
这是身份验证控制器:
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();
});
}