首页 > 解决方案 > Hashing passwords using bcrypt without a database

问题描述

I created an endpoint to register new users, /register.

Since I'm not using a database, I'm updating an array by pushing the new user into it, and then writing this new array into a json file using fs.writeJSONFile().

Below is the code for registering a new user:

router.post("/register", m.checkFieldsPost, async (req, res) => {
  const { email, password } = req.body;
  const id = { id: helper.getNewId(users) };

  try {
    const user = await helper.findUser(users, email);
    console.log(`user is ${user}`);
    if (user)
      return res.status(400).json({
        message: "That user already exists!",
      });
    // Generate salt
    const salt = await bcrypt.genSalt(10);

    // Hash password
    const hashedPassword = await bcrypt.hash(password, salt);

    const newUser = {
      ...id,
      password: hashedPassword,
      email,
    };

    await users.push(newUser);
    await helper.writeJSONFile(filename, users);

    return res.status(201).json({
      message: `New user was created`,
      user: newUser,
      originalPassword: password,
      hashedPassword,
    });
  } catch (err) {
    res.status(500).json({ message: err.message });
    // res.status(500).json({ message: "Mesasge from the catch block" });
  }
});

The problem seems to be in my function that looks for a user in the database:

function findUser(array, email) {
  return new Promise((resolve, reject) => {
    const row = array.find((r) => r.email == email);
    if (!row) {
      reject({
        message: "User not found",
      });
      reject(null);
    }
    resolve(row);
  });
};

I'm trying to register a new user and I first check if the email already exists in the json file using the function above:

const user = await helper.findUser(users, email);

However, it seems that if the user is not found, the function call ends and I'm sending back a status code to the client. Is there a problem in the way I'm rejecting the promise? How could I return null from a promise rejection?

标签: apiexpresscrudbcrypt

解决方案


拒绝承诺将其标记为拒绝/失败。然后await关键字将抛出您传递给的任何内容reject(...)。因此,当找不到用户时,您的代码会异常中止。你应该在你的await helper.findUser(...)电话周围放一个try/catch。或者,resolve(null)如果您希望 await 返回 null 而不是抛出,请调用。

这也意味着您不应该调用reject两次,或者更糟的是,调用这两个reject并且resolve与您的代码当前所做的相同。调用其中一个函数并不等同于返回,该函数仍然必须干净地返回。


推荐阅读