Home > OS >  Node.js Sequelize forbid some paramaters in model.Update
Node.js Sequelize forbid some paramaters in model.Update

Time:08-11

I'm making an API with Express and Sequelize

I want my user to be able to update some entries without having a defined number of params.

For example, if I have the following "Books" database table :

Name Type
id int
name varchar
description text
userId int

I have a post route to update the entry :

function(req, res)
{
    
    var screenUpdate = Book.update(req.body,
        {where: {id: req.body.id}})
        .then(function(){
            return res.status(201).json({
                "data": "ok"
            });
        })
        .catch(function(err){
            return res.status(500).json({'error':"Impossible de modifier."}); 
        });
}

In this case, the user will put in the request the params that it need, for example name, description but it doesn't prevent it to add id or userId which could break the database. How could I forbid those parameters from being updated by that request ?

Thank you in advance.

CodePudding user response:

You should limit or filter the req.body. Remove sensitive fields before passing them into the update function. One simple way is:

function(req, res) {
  const { id, userId, ...safeFields } = req.body;
  const screenUpdate = Book
    .update(safeFields, { where: { id: req.body.id } })
    .then(() => res.status(201)
      .json({
        data: 'ok',
      }))
    .catch((err) => res.status(500)
      .json({ error: 'Impossible de modifier.' }));
},

As a safer option, define a white list of allowed fields:

function(req, res) {
  // Field names that are allowed to edit
  const allowedFields = ['BookName', 'Author', 'Date'];

  // Extract values of allowed fields if presented in the body
  const safeFields = allowedFields
    .filter((x) => req.body[x] != null)
    .reduce((state, x) => ({ ...state, [x]: req.body[x] }), {});

  const screenUpdate = Book
    .update(safeFields, { where: { id: req.body.id } })
    .then(() => res.status(201).json({ data: 'ok' }))
    .catch((err) => res.status(500).json({ error: 'Impossible de modifier.' }));
},

If allowed fields are wider than banned ones, use a reverse approach:

function(req, res) {
  // Field names that shouldn't update
  const blackList = ['id', 'userId'];

  // Make a copy of the body then remove banned fields
  const safeFields = { ...req.body };
  blackList.forEach((x) => delete safeFields[x]);

  const screenUpdate = Book
    .update(safeFields, { where: { id: req.body.id } })
    .then(() => res.status(201).json({ data: 'ok' }))
    .catch((err) => res.status(500).json({ error: 'Impossible de modifier.' }));
},
  • Related