使用 Knex 和 Argon2 未将密码保存到数据库

Password not being saved to database using Knex and Argon2

我正在尝试为我的数据库添加几个样本用户。我将 Knex 用于我的 postgres 数据库,将 npm-argon2 用于密码散列。据我所知,我的简单 hasing 函数有效,但是当我在插入时 运行 它时,它会保存一个空对象:

const argon = require('argon2');


exports.seed = function (knex) {
  return knex('users').del()
    .then(function () {

      const password_hash = async (password) => {
        let hash = await argon.hash(password);
        console.log(hash); // this works
        return hash; // this does not
      }

      return knex('users').insert([
        { username: 'John Doe', email: 'johndoe@example.com', password_hash: password_hash('abc123') },
        { username: 'Jane Doe', email: 'janedoe@example.com', password_hash: password_hash('abc123') }
      ]);
    });
};

当我 运行 我的种子文件时,我可以看到哈希被正确地控制台登录到终端中,但是当我重新检查 postgres 时,它们都被保存为 {}。我做错了什么?

您的 password_hash 函数 returns 承诺(通过 async 关键字)。插入是在不等待生成散列的情况下进行的(即使您看到的是控制台输出)。你要做的是一步一步来:

const users = [
  { username: 'John Do', email: 'johndoe@example.com', password: 'abc123' }
]
for (let user of users) {
  user.password_hash = await password_hash(user.password)
}

// Write the users to the db, but omit the plaintext `password` property
return knex('users').insert(users.map(({ password, ...rest }) => rest)

您的包含函数需要声明 async