【问题标题】:The best solution for control access to models in strongLoopstrongLoop中控制模型访问的最佳解决方案
【发布时间】:2016-04-10 11:15:22
【问题描述】:

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

【问题讨论】:

  • 是否要禁用 CustomUsers 的公共访问权限?
  • 是的。我只想为我的 RemoteMethod 启用访问权限。

标签: node.js loopbackjs strongloop


【解决方案1】:

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

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

  1. 如何在 api 中禁用 apply 'where' 过滤器。
  2. 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。

【讨论】:

  • 谢谢。第二种方法,我可以使用 RemoteMethod 代替基本 API 并为 ir 设置 ACL 吗?
  • 是的,您可以使用自己的acl定义远程方法并将其与Item模型相关联。
【解决方案2】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    • 1970-01-01
    相关资源
    最近更新 更多