【问题标题】:How to properly use UNNEST without being vulnerable to sql injections如何正确使用 UNNEST 而不会受到 sql 注入的影响
【发布时间】:2021-04-13 23:00:25
【问题描述】:

我正在尝试使用 Express.js 和 postgresql 在多对多关系表中一次插入多行。下面的解决方案有效,但是,我知道因为我没有使用值传递 homeType,所以它很容易受到 sql 注入。

创建家庭控制器

 const {
    title,
    description,
    rules,
    telephone,
    homeType, // Array of ids example [1,2]
  } = req.body;

  try {
    const results = await db.query(
      'WITH step_one AS (INSERT INTO home (home_title, home_description, rules, telephone, user_account_id, created_on) VALUES ($1, $2, $3, $4, $5, NOW()) RETURNING home_id) INSERT INTO home_category (home_id, home_category_id) SELECT home_id, UNNEST(ARRAY' +
        JSON.stringify(homeType) +
        ') FROM step_one',
      [title, description, rules, telephone, req.user]
    );
  } catch (err) {
    console.error(err.message);
    return res.status(500).send('Server Error');
  }

  res.status(201).json({ message: 'Home created successfully' });

如何以正确的方式从数组中插入多行?

【问题讨论】:

    标签: javascript node.js postgresql express node-postgres


    【解决方案1】:

    通过传递值并将参数输入转换/强制转换为查询语句中的实际数组来防止 SQL 注入。

    要在 postgresql 中将对象转换为整数数组,请使用 $6::integer[]

    完整查询如下:

     const results = await db.query(
          'WITH step_one AS (INSERT INTO home (home_title, home_description, rules, telephone, user_account_id, created_on) VALUES ($1, $2, $3, $4, $5, NOW()) RETURNING home_id) INSERT INTO home_category (home_id, home_category_id) SELECT home_id, UNNEST($6::integer[]) FROM step_one',
          [title, description, rules, telephone, req.user, homeType]
        );
    

    【讨论】:

      猜你喜欢
      • 2021-12-28
      • 2011-07-16
      • 1970-01-01
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多