gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:32:30 25 4
gpt4 key购买 nike

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

最佳答案

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

当然,您问了两个不同的问题。

  1. 如何在 api 中禁用应用“where”过滤器。
  2. CustomUser 如何仅访问他的项目。
<小时/>

对于第一个问题,您可以使用环回钩子(Hook)并根据您想要的任何内容设置where过滤器。这样,您就不必编写新的远程方法。

Item.json:

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

对于下一个问题,您必须为两个模型使用一些 acl 和关系,如下所示:

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

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

下一个在 CustomUser.json model 定义了可以使用 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 模型中,其他用户无法访问他的 Item。

关于node.js - 在strongLoop中控制模型访问的最佳解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36529000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com