html - 在nodejs中使用bcrypt登录
问题描述
我很难集成 bcrypt 以尝试使我的登录系统安全。
我基本上得到了用户输入的用户名、密码,并尝试将其与我的数据库中的散列密码进行比较。这就是我所拥有的。
const inputUsername = req.body.inputUsername;
const inputPassword = req.body.inputPassword;
var userLogin = "select * from login where USERNAME = ?"
ibmdb.open(ibmdbconnMaster, function(err, conn) {
if (err) return console.log(err);
conn.query(userLogin, [inputUsername], function(err, rows) {
if (err) {
console.log(err)
}
if (rows.length > 0) {
var pass = ""
for (var i = 0; i < rows.length; i++) {
pass = rows[i]['PASSWORD'];
console.log(pass)
bcrypt.compare(inputPassword, hash, function(err, result) {
if (pass == result) {
console.log("this works")
userAuth = true;
res.redirect('/index')
}
})
}
console.log("does not work")
} else {
userAuth = "false";
res.render('login.ejs')
alert('Incorrect username or password. Please try again')
}
conn.close(function() {
console.log('closed the function /login');
});
})
})
现在发生的事情是我收到错误,ReferenceError: hash is not defined
不知道如何解决这个问题。提前致谢
解决方案
你在哪里定义的hash
?我在您的代码中没有看到它。
这是我在 bcrypt/node/express 中使用的身份验证路由的示例:
const Users = require("../users/users-model.js");
router.post("/register", (req, res) => {
// Pull the user's credentials from the body of the request.
const user = req.body;
// Hash the user's password, and set the hashed password as the
// user's password in the request.
const hash = bcrypt.hashSync(user.password, 10);
user.password = hash;
Users.add(user)
.then((newUser) => {
const token = generateToken(newUser);
res
.status(201)
.json({ created_user: newUser, token: token, user_id: newUser.id });
})
.catch((err) => {
res.status(500).json({
message: "There was an error adding a user to the database",
err,
});
});
});
router.post("/login", (req, res) => {
const { username, password } = req.body;
Users.findBy({ username })
.first()
.then((user) => {
if (user && bcrypt.compareSync(password, user.password)) {
const token = generateToken(user);
res
.status(200)
.json({
username: user.username,
first_name: user.first_name,
last_name: user.last_name,
email: user.email,
token: token,
user_id: user.id,
});
} else {
res.status(401).json({ message: "Invalid Credentials" });
}
})
.catch((err) => {
res.status(500).json(err);
});
});
function generateToken(user) {
const payload = {
userid: user.id,
username: user.username,
};
const options = {
expiresIn: "1h",
};
const token = jwt.sign(payload, secrets.jwtSecret, options);
return token;
}
module.exports = router;
推荐阅读
- azure - Azure Kusto Java SDK 获取查询结果的所有列
- angular - Rxjs 如何在智能组件中等待来自动态组件的所有 observables 完成
- java - counter.Cancel(); 不在 OnStop() 中执行;方法
- python - 如何使用 schema.org 在 RDFlib 中描述具有最小值/最大值的温度?
- swift - 'xxx' 的模糊使用
- r - 在 R 中抓取 RSS url
- vue.js - Nuxt配置全局变量全局变量属性无法访问是什么原因
- java - 我的插入无法通过 PreparedStatement 实现
- c# - 我可以扩展命令类,以便自动禁用绑定到它的按钮吗?
- cdi - 应用程序范围的托管 bean 未初始化