Question

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?

Was it helpful?

Solution

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"
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top