Saturday, 17 October 2020

Where to put the express-validation sanitzer?

I run an express application which checks on a post route if fields are "ok":

const { body, sanitizeBody, validationResult } = require('express-validator');
exports.freelancer_create_post = [
  // Validate fields.
  body('family_name').isLength({ min: 1 }).trim().withMessage('Family name must be specified.'),
  body('date_of_birth', 'Invalid date of birth').optional({ checkFalsy: true }).isISO8601(),
  body('email_address').isEmail().withMessage('Must be a valid email address.'),
  // Sanitize fields.
  sanitizeBody('date_of_birth').toDate(),
  sanitizeBody('email_address').normalizeEmail(),
  sanitizeBody('family_name').escape(),
  sanitizeBody('username').escape(),
(req, res, next) => {...}
];

Works fine. But now I would like to add it to the passport js local strategy middleware chain:

const { body, sanitizeBody, validationResult } = require('express-validator');
exports.localStrategy = function (passport) {
    // Configure the local strategy for use by Passport.
    passport.use(new Strategy({
        usernameField: 'email',
        passwordField: 'password',
        passReqToCallback: true,
    },
     [body('family_name').isLength({ min: 1 }).trim().withMessage('Family name must be specified.')],
     (req, email, password, cb) => {...}
    ))
};

How would I do that?

I've tried to insert an array in between (see code above), but it returns a TypeError: this._verify is not a function error.

Dirty solution is to use the 'mongo-sanitize' module and check each field, but I would like to understand how to set this up correctly.



from Where to put the express-validation sanitzer?

No comments:

Post a Comment