gpt4 book ai didi

node.js - 如何使用 postgres 查询修复函数以防止 SQL 注入(inject)

转载 作者:行者123 更新时间:2023-11-29 12:15:31 25 4
gpt4 key购买 nike

我需要帮助修复我编写的函数(在 node.js 无服务器微服务中)以防止 sql 注入(inject)。我是安全主题的新手,所以任何正确方向的想法或观点都会很棒,谢谢!

这是 RecipientAlerts.js 中的函数:

  updateRecipient(email, body, callback) {
helper.removeRecipient(this.db, email) // clears old data
.then(() => {
const values = Object.keys(body).map(industry =>
body[industry].map(company =>
`('${company}', '${industry}', '${email}')`).join(', ')).join(', ');
const insert =`INSERT INTO recipient_list(company, industry, email_address) VALUES `;
this.db.queries.none(insert + values)
.catch((error) => {
console.log(error, 'error on insert query', callback);
});
})
.then(() => {
console.log('successfully updated', null, callback);
})
.catch((error) => {
console.log(error, 'failed to update recipient', callback);
});
}

这是 recipient.json:

{ 
"pathParameters": {
"email": "john@gmail.com"
},
"body": {
"tech": ["Apple"],
"hospitality": ["McDonalds", "Subway"],
"banking": ["Citi", "HSBC"]
}
}

预期结果(我目前正在获得并希望保持不变)是:recipient_list表:

company       |  industry   | email_address
______________|_____________|________________
Apple | tech | john@gmail.com
--------------|-------------|---------------
McDonalds | hospitality | john@gmail.com
--------------|-------------|---------------
Subway | hospitality | john@gmail.com
--------------|-------------|---------------
Citi | banking | john@gmail.com
--------------|-------------|---------------
HSBC | banking | john@gmail.com

最佳答案

Multi-Row Inserts 之后pg-promise 的示例, 声明一个 ColumnSet对象一次:

const cs = new pgp.helpers.ColumnSet([
'company',
'industry',
{name: 'email_address', prop: 'email'}
], {table: 'recipient_list'});

然后您可以将代码更改为:

updateRecipient(email, body, callback)
{
helper.removeRecipient(this.db, email) // clears old data
.then(() => {
const insert = pgp.helpers.insert(body, cs); // generating the INSERT query
this.db.queries.none(insert) // executing the INSERT query
.catch((error) => {
console.log(error, 'error on insert query', callback);
});
})
.then(() => {
console.log('successfully updated', null, callback);
})
.catch((error) => {
console.log(error, 'failed to update recipient', callback);
});
}

SQL 将以这种方式安全地生成,并且不受 SQL 注入(inject)的影响。

关于node.js - 如何使用 postgres 查询修复函数以防止 SQL 注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56537572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com