在strongLoop中控制访问模型的最佳解决方案

时间:2016-04-10 11:15:23

标签: node.js loopbackjs strongloop

我是StrongLoop的新手。 我有2个模型(CustomUserItem)。 我希望任何CustomUser都可以访问他的Items。 我不想使用StrongLoop公开的默认API,因为我不希望CustomUsers能够使用这些API定义过滤器。 我定义了我的RemoteMethod,它根据内部过滤器返回项目。 我的问题: 我应该检查当前用户并返回他的相关项目,还是我可以在StrongLoop中使用ACL来解决这个问题? 如果ACL是正确的答案,我应该在哪里插入我的RemoteMethod(CustomUser模型或Item模型)以及如何定义使用ACL的正确设置?

2 个答案:

答案 0 :(得分:2)

是的,这是可能的。 Loopback非常灵活。

当然,你问过两个不同的问题。

  1. 如何在api中禁用“where”过滤器。
  2. CustomUser如何只访问他的物品。
  3. 对于第一个问题,您可以使用环回挂钩并根据您想要的任何内容设置过滤器。这样,您就不必强制编写新的远程方法。

    Item.json:

    Item.observe('access', function limitToTenant(ctx, next) {
     ...
     ctx.query.where.tenantId = loopback.getCurrentContext().tenantId;
    ...
     next();
    });
    

    对于下一个问题,你必须为你的两个模型使用一些acls和关系:

    首先,禁用访问Item.json模型中的所有远程方法。

    "acls": [
     {
      "accessType": "*",
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "DENY"
     }
    ]
    

    下一个CustomUser.json模型定义了可以使用Item模型的哪些方法:

    "acls": [
        {
        "principalType": "ROLE",
        "principalId": "$owner",
        "permission": "ALLOW",
        "property": "__create__items"
        },
        {
        "principalType": "ROLE",
        "principalId": "$owner",
        "permission": "ALLOW",
        "property": "__get__items"
        },
        {
        "principalType": "ROLE",
        "principalId": "$owner",
        "permission": "ALLOW",
        "property": "__count__items"
        }
        ...
    ]
    

    接下来,定义CustomUser和Item模型之间的关系。

    Item.json 中的

    "relations": {
        "customUser": {
        "type": "belongsTo",
        "model": "CustomUser",
        "foreignKey": "ownerId"
        }
    }
    
    CustomUser.json中的

    "relations": {
        "items": {
        "type": "hasMany",
        "model": "Item",
        "foreignKey": "ownerId"
        }    
    }
    

    然后创建新用户并使用收到的accessToken登录,并保留userId以进行后续步骤。

    现在,如果您想发布新项目,可以使用此API。

    POST (items data) : api/CustomUser/{userId}/items/
    

    要获得他的物品,你可以使用:

    GET : api/CustomUser/{userId}/items/
    

    这样,ownerId将自动保存在Item模型中,而其他每个用户都无法访问他的Items。

答案 1 :(得分:0)

根据环回documentation,必须单独禁用每个方法。

var isStatic = true;
CustomUser.disableRemoteMethod('deleteById', isStatic);

但即使禁用了远程方法,也可以调用远程方法。

只有在您打算执行任何authorisation控制时才需要ACL。