限制字段​​设置在Sails.js模型中 [英] Restricting fields from being set in Sails.js Model

查看:137
本文介绍了限制字段​​设置在Sails.js模型中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个这样的字段的模型:

So I have a model with some fields like so:

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

我正在使用帆船蓝图结构,所以它自动映射一切。但是,有时候我有一些字段,如 loggedinAt ,这些字段是严格内部的,我不希望用户可以设置它们。

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.

如果我使用 loggedinAt 字段发布发布请求,它将设置它。如何限制这一点?

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

推荐答案

您可以使用策略来限制此行为。在 api / policies / restrictUserCreate.js 中:

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();

}

或者只是忽略某些字段(Sails v0.10只需使用黑名单

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();

}

然后在 config / policies.js

Then in config/policies.js:

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

这篇关于限制字段​​设置在Sails.js模型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆