【问题标题】:Update value from database with the hashed content from another column使用另一列中的散列内容更新数据库中的值
【发布时间】:2020-01-09 04:22:32
【问题描述】:
我正在尝试创建一个 nodejs 迁移以向我的表中添加一个新列,并使用同一行中另一列的散列内容更新所有旧记录。顺便说一句,我正在使用 Knex。
我尝试使用 bcrypt 对内容进行哈希处理,但在访问行中的内容时遇到了一些困难。我现在拥有的是这样的:
return knex.raw(
`UPDATE ${schema}.${tableName} tm
SET hashed_transfer_information = ${await bcrypt.hash(tm.transfer_method_information), 10}`
);
问题是这样我无法访问行中的内容?
你们能帮忙吗?
【问题讨论】:
标签:
javascript
node.js
postgresql
bcrypt
knex.js
【解决方案1】:
你可以在 postgres 中做,但我不知道那里使用的河豚算法是否与你的客户端 bcrypt 实现兼容。
`UPDATE ${schema}.${tableName}
SET hashed_transfer_information
= crypt(transfer_method_information,gen_salt('bf', 10))`
您可能需要先通过执行 (SQL) 来启用 pgcrypto 扩展:
CREATE EXTENSION pgcrypto;
【解决方案2】:
使用 knex 语法完成钳位的答案:
knex('tableName').withSchema('schema')
.update(
'hashed_transfer_information',
knex.raw(`crypt(transfer_method_information, gen_salt('bf', 10))`)
)
【解决方案3】:
谢谢clamp 和Mikael,这很有趣。我从不费心在数据库中散列密码
之前!
为了检查clamp关于兼容性的问题,我跑了以下:
const secret = "wombats";
const notTheSecret = "notwombats";
knex("users")
.update("hash", knex.raw(`crypt('${secret}', gen_salt('bf', 10))`))
.then(() =>
knex("users").then(async users => {
for (let user of users) {
console.log(
`Password is '${secret}' ...`,
await bcrypt.compare(secret, user.hash)
);
console.log(
`Password is '${notTheSecret}' ...`,
await bcrypt.compare(notTheSecret, user.hash)
);
}
})
);
事实证明,它工作得很好:
Password is 'wombats' ... true
Password is 'notwombats' ... false
Password is 'wombats' ... true
Password is 'notwombats' ... false