Sanitize user input in Mongoose

前端 未结 2 564
广开言路
广开言路 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: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);
    

提交回复
热议问题