Restricting fields from being set in Sails.js Model

时光毁灭记忆、已成空白 提交于 2019-12-12 09:19:43

问题


So I have a model with some fields like so:

// ...
slug: {
  type: 'string',
  required: true,
  alphanumeric: true,
  minLength: 3,
  maxLength: 16
},
loggedinAt: 'date',
// ...

I'm using the Sails blueprint structure so it automatically maps everything. However, sometimes I have fields like loggedinAt which are strictly internal and I don't want them to be able to be set by the user.

As it stands if I make a post requests with the loggedinAt field it will set it. How can I restrict this?


回答1:


You can use a policy to restrict this behavior. In api/policies/restrictUserCreate.js:

module.exports = function (req, res, next) {

    // Check for the "loggedInAt" field in the request
    if (req.param('loggedInAt')) {
       return res.badRequest("Nuh uh, you can't set that!");
    }

    return next();

}

or, to just ignore certain fields (Sails v0.10.x only), use the blacklist:

module.exports = function (req, res, next) {

    // Make sure blacklist object exists, and use existing one if possible,
    // since this policy could be chained
    req.options.values = req.options.values || {};
    req.options.values.blacklist = req.options.values.blacklist || [];
    // Add restricted fields to the blacklist
    req.options.values.blacklist.push('loggedinAt');
    return next();

}

Then in config/policies.js:

// Assuming your controller is "UserController"
UserController: {
    create: "restrictUserCreate"
}


来源:https://stackoverflow.com/questions/24042277/restricting-fields-from-being-set-in-sails-js-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!