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

The best solution for control access to models in strongLoop

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

根据环回 documentation 每种方法都必须单独禁用。

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

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

仅当您打算执行任何 authorisation 控制时才需要 ACL。

是的,这是可能的。环回非常灵活。

当然,你问了 2 个不同的问题。

  1. 如何在 api.
  2. 中禁用应用 'where' 过滤器
  3. CustomUser 如何只访问他的项目。

对于第一个问题,您可以使用环回挂钩并根据您的情况设置 where 过滤器 want.in 这样,您就不会被迫编写新的远程方法。

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 以用于后续步骤。

现在如果你想 post 新项目你可以使用这个 api。

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

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

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

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