简体   繁体   English

SailsJS。 检查请求中元素的groupID是否与用户组相同的通用策略

[英]SailsJS. Generic policy which check if groupID of element in request is the same as user's group

I have big API and I'm using blueprints as it is really convenient for most of operations. 我有大量的API,并且正在使用蓝图,因为它对于大多数操作而言确实很方便。 It is multi-tenant application, so every element has groupID field. 它是多租户应用程序,因此每个元素都有groupID字段。

I need to have policy which will check if element which is going to be edited/deleted belongs to user's group. 我需要有一个策略来检查要编辑/删除的元素是否属于用户组。 I have user's groupID in request already injected by JWT policy, but how can I make policy to generic policy which will check appropriate model for id and compare it with user id ? 我的请求已经由JWT策略注入了用户的groupID,但是如何使策略成为通用策略,该策略将检查ID的适当模型并将其与用户ID进行比较? It can't be done by groupID from request as hacker can use his JWT token and put his groupID in request but access not his element. 黑客无法使用来自请求的groupID来完成此操作,因为黑客可以使用其JWT令牌并将其groupID放入请求中,但不能访问其元素。 IS it possible or I have to create separate policy per model? 是否可以,或者我必须为每个模型创建单独的策略?

I found it. 我找到了。

You can get modelName from req.options.model when you are using Blueprints. 使用蓝图时,可以从req.options.model获取modelName

Unfortunately you can't use this[modelName] as option is giving you model name starting with small letter, so first you have to upper case first letter with eg var modelName = req.options.model.charAt(0).toUpperCase() + req.options.model.slice(1); 不幸的是,您不能使用this[modelName]因为选项为您提供以小写字母开头的模型名称,因此首先您必须以大写首字母加上例如var modelName = req.options.model.charAt(0).toUpperCase() + req.options.model.slice(1);

and then you are free to use this[modelName].whateverYouNeed 然后您可以随意使用this[modelName].whateverYouNeed您需要this[modelName].whateverYouNeed

I used it for generic policy to let user editing only his own group elements. 我将其用于一般策略,以允许用户仅编辑自己的组元素。

var modelName = req.options.model.charAt(0).toUpperCase() + req.options.model.slice(1)
  var elementID = null

  if (req.params.id) { // To handle DELETE, PUT
    elementID = req.params.id
  }
  if (req.body.id) { // To handle POST
    elementID = req.body.id
  }

  this[modelName].findOne({
    id: elementID
  }).exec(function(err, contextElement) {
    if(err) {
      return res.serverError(err)
    }
    if(contextElement.group=== req.user.group.id) {
      sails.log('accessing own: ' + modelName)
      return next()
    }
    else {
      return res.forbidden('Tried to access not owned object')
    }
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM