无法使用bcrypt哈希密码 [英] Cannot hash password with bcrypt
问题描述
我一直在尝试在用户中实现bcrypt,以便可以使用JWT进行身份验证;但是,每当我尝试使用bcrypt哈希密码时,它都会在第一个if语句中引发错误.我正在使用express.js作为我的框架.我还必须提到,我没有使用数据库,而用户存储在另一个文件中的数组中.我是Node的新手,但我仍在努力了解它.
I've been trying to implement bcrypt within my user so I can use JWT for authentication; however whenever I try to hash my password with bcrypt it throws and error in the first if statement. I am using the express.js as my framework. I also have to mention that I am not using a database and the user is stored within an array in a different file. I am new to node and I'm still trying to understand it.
我的用户路线
const express = require('express');
const router = express.Router();
const users = require('../../Users');
const bcrypt = require('bcrypt');
router.post('/signup', (req, res, next) => {
bcrypt.hash(req.body.password, 10, (err, hash) => {
if (err) {
return res.status(500).json({
error: err
});
} else {
const user = {
id: users.length + 1,
userName: req.body.userName,
email: req.body.email,
password: hash,
firstName: req.body.firstName,
lastName: req.body.lastName,
}
user
.then(result => {
console.log(result)
res.status(201).json({
message: 'User created'
})
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
})
}
})
})
客户请求
{
"email": "test@test.com",
"password": "testerpassword",
"userName": "test",
"firstName": "teste",
"lastName": "tester"
}
推荐答案
创建一个使用密码并返回并加密的辅助方法:
Make a helper method that takes the password and returns and encrypted one:
const crypto = require("crypto");
const hashThePassword = (str) => {
if (typeof str == "string" && str.length > 0) {
const hash = crypto
.createHmac("sha256", config.hashingSecret)
.update(str)
.digest("hex");
return hash;
} else {
return false;
}
};
配置对象包含一个任意的秘密字符串.
The config object contains an arbitrary secret string.
这篇关于无法使用bcrypt哈希密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!