是的,这是可能的。 Loopback 非常灵活。
当然,你问了两个不同的问题。
- 如何在 api 中禁用 apply 'where' 过滤器。
- CustomUser 如何仅访问他的项目。
对于第一个问题,您可以使用环回挂钩并根据需要设置过滤器。这样,您不必编写新的远程方法。
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模型中定义可以使用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。