未提供身份验证时从Loopback获取限制响应

时间:2017-10-20 11:12:48

标签: loopbackjs loopback

我无法找到在文档中执行此操作的方法,而且我已经在Stack Overflow上进行了调查。我想在用户登录之前向用户展示我的JSON响应的有限视图。

所以,作为一个例子,我有一个我想在网上销售的电子书。我希望他们只在未登录时看到书籍的预览链接(epubFile.notAuthoried),以及登录时书籍的完整链接(epubFile.authorized)。两个链接都表示在同一个表格中。

[
  {
    "title": "string",
    "subTitle": "string",
    "isPublished": true,
    "publicationDate": "2017-10-20T11:07:31.258Z",
    "epubFile": {
      "notAuthorized": "filename-noauth.epub"
      "authorized": "filename-auth.epub"
    }
    "id": "string",
    "createdOn": "2017-10-20T11:07:31.258Z",
    "updatedOn": "2017-10-20T11:07:31.258Z"
  }
]

甚至可以在环回中过滤掉API端点中的字段吗? 或者我是否需要构建新的自定义API端点?

1 个答案:

答案 0 :(得分:2)

首先,您必须将findfindById方法的权限设置为$ everyone,以便授权和未授权用户都可以调用它们

{     
  "name": "eBook",
   "base": "PersistedModel",
   [...]
   "acls": [
     "accessType": "READ",
     "principalType": "ROLE",
     "principalId": "$everyone",
     "permission": "ALLOW",
     "property":["find", "findById]
    ]
}

接下来,您必须挂钩远程方法并根据用户是否登录来修改响应

const previewProperites = ['title', 'subTitle', etc...]
Ebook.afterRemote('find', (ctx, ebooks, next) => {
  // pseudo code
  if(!ctx.options.accessToken){
    // no user logged in, only keep preview properties
    ebooks.forEach(book => {
      // get the properties of the book
      var eBookProperties = Object.keys(book.__data);

      eBookProperties.forEach(bookProp =>{
        if(!previewProperties.some(pProp => pProp === bookProp)){
          // ebook property not in preview list, so remove it
          delete book.__data[bookProp]; // .__data is where loopback keeps its actual data
        }
      });
    });
  }
  next();
}