在strongLoop中控制对模型的访问的最佳解决scheme
我是StrongLoop的新手。 我有2个模型( CustomUser
和Item
)。 我想要任何CustomUser
有权访问他的Items
。 我不希望使用StrongLoop公开的默认API,因为我不希望CustomUsers能够使用这些API定义filter。 我定义了基于内部filter返回项目的RemoteMethod。 我的问题:我应该检查当前的用户,并返回他的相关项目,或者我可以使用ACL在StrongLoop这个事情? 如果ACL是正确的答案,我应该在哪里插入我的RemoteMethod( CustomUser
模型或Item
模型),以及如何定义使用ACL的正确设置?
是的,这是可能的。 环回非常灵活。
当然,你问了2个不同的问题。
- 如何禁用在API中应用'where'filter。
- CustomUser如何访问他的项目。
对于第一个问题,你可以使用loopback钩子,并设置基于你想要的任何filter。这样,你不会强迫写新的远程方法。
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" } }
然后创build新的用户并使用收到的accessTokenlogin并保留userId以进行下一步。
现在,如果你想发布新的项目,你可以使用这个API。
POST (items data) : api/CustomUser/{userId}/items/
为了得到他的物品,你可以使用:
GET : api/CustomUser/{userId}/items/
通过这种方式,ownerId将自动保存在Item模型中,而其他用户不能访问他的Items。
根据回送文档,每个方法都必须单独禁用。
var isStatic = true; CustomUser.disableRemoteMethod('deleteById', isStatic);
但即使被禁用,也可以调用远程方法。
只有当您打算执行任何授权控制时才需要ACL。