Sanitize user input in Mongoose

前端 未结 2 527
广开言路
广开言路 2021-02-19 00:49

Except for this fairly uninformative answer and another unpopular answer, I can\'t seem to find any resources about sanitizing user input using Mongoose.

There\'s a blog

相关标签:
2条回答
  • 2021-02-19 01:39

    There is a new tool providing auto control of coming URL and html body data. https://www.npmjs.com/package/content-filter

    Also native escape() method might be used for to protect the database.

    Run the code snippet below to see the results.

    let a = "{$gt:25}"
    console.log(a)
    console.log(escape(a))

    0 讨论(0)
  • 2021-02-19 01:46

    It seems like the mongo-sanitize npm module is the place to start for the raw escaping functionality. Honestly this sounds more appropriate at the connect/express middleware layer because at the mongoose layer, by design, the code does not exert any expectations on the query/update parameters in terms of whether they are written by the application developer (in which case they must not be sanitized or they won't function correctly) or involve user input (which must be sanitized). Thus I'd recommend middleware functions to sanitize the most common places for user input to enter: req.body, req.query, and req.params. So for example you might do something like (sketch):

    var json = require("body-parser").json;
    var sanitize = require("mongo-sanitize");
    
    function cleanBody(req, res, next) {
      req.body = sanitize(req.body);
      next();
    }
    
    function updateUser(req, res) {
      //...
      // safe to build an update query involving req.body here
    }
    app.put("/api/users", json(), cleanBody, updateUser);
    
    0 讨论(0)
提交回复
热议问题