无法使用bcrypt哈希密码

问题描述 投票:0回答:1

我一直在尝试在我的用户中实现bcrypt,所以我可以使用JWT进行身份验证;但是,每当我尝试使用bcrypt散列我的密码时,它会在第一个if语句中抛出错误。我使用express.js作为我的框架。我还必须提到我没有使用数据库,用户存储在不同文件的数组中。我是节点的新手,我仍然试图理解它。

我的用户路线

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": "[email protected]",
    "password": "testerpassword",
    "userName": "test",
    "firstName": "teste",
    "lastName": "tester"
}
node.js express jwt bcrypt
1个回答
0
投票

创建一个获取密码并返回并加密的辅助方法:

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;
  }
};

config对象包含任意秘密字符串。

© www.soinside.com 2019 - 2024. All rights reserved.