【问题标题】:How to exclude characters from express-validators escape() function如何从 express-validators escape() 函数中排除字符
【发布时间】:2020-01-11 15:58:42
【问题描述】:

我正在使用 express-validator 的检查来验证用户输入,我想知道我是否可以从测试中排除字符?我有

check("profile.about").trim().escape()

将 HTML 中使用的任何字符转换为其等效的 HTML 实体,但如果用户输入撇号,则会导致不希望的结果。有没有办法从escape() 方法中过滤掉撇号?如果没有,是否有人对我如何模仿escape() 并放弃' 有任何提示。谢谢

【问题讨论】:

  • 这是一个奇怪的问题。因为允许使用撇号会使您面临 sql 注入和跨站点脚本攻击。这将使转义变得毫无用处。
  • 为什么要保留撇号?
  • @yonbav 我使用的是 noSQL 数据库,所以这仍然是个问题吗?我还有其他个人资料字段,包括添加最喜欢的作者,如果用户输入名字 O'Brian 看起来真的很傻
  • 我无法确定这是否会成为问题,这在很大程度上取决于您如何实现服务器。在将值返回给用户之前,我建议使用 unescape 的任何方式

标签: javascript node.js express validation


【解决方案1】:

可以立即添加另一个中间件来完成此操作...

unescape-middleware.js

module.exports = (escaped, char) => function (req, res, next) {
    unescapeCharacter(req.params, escaped, char);
    unescapeCharacter(req.query, escaped, char);
    unescapeCharacter(req.body, escaped, char);
    return next();
}

function unescapeCharacter (obj, escaped, char) {
    for (const key in obj) {
        // Replace the escaped version with the character
        obj[key] = obj[key].replace(new Regex(escaped, "g"), char);
    }
}

然后这样使用......

app.js

const { check } = require("express-validator");
const unescape = require("./path/to/unescape/middleware.js");

app.get(
    "/some/route", 
    check("profile.about").trim().escape(), 
    unescape("'", "'"), 
    require("./path/to/router/handler.js")
);

我相信这应该可以解决问题...

【讨论】:

    猜你喜欢
    • 2018-08-07
    • 2022-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-26
    相关资源
    最近更新 更多