简体   繁体   中英

Cannot hash password with bcrypt

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.

My user routes

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

Client request

{
    "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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM