Cannot hash password with bcrypt

2019-08-25 18:48发布

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

1条回答
Ridiculous、
2楼-- · 2019-08-25 19:15

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.

查看更多
登录 后发表回答