如何使用环回保护不同角色的属性
How to protect properties for different roles using loopback
我只是想知道您将如何限制 属性 对 $owner 角色的访问权限。例如,在我的例子中,我有一个有作者的笑话。作者以用户为基础。我希望其他 "Authers" / 用户看到谁创造了这个笑话,但他们不应该看到作者的电子邮件,只有当作者是笑话本身的 $owner 时,才应该可以显示他们的电子邮件,只是为了这个案例。
查看内置用户模型,您可以看到他们使用 hidden 功能来隐藏密码,但是将其用于他们的电子邮件也会隐藏他们的电子邮件$owner,这不是我想要的
如果有什么不清楚的地方,请告诉我。
提前致谢
您可以创建自己的角色解析器。有关示例,请参见 https://github.com/strongloop/loopback-example-access-control/blob/master/server/boot/role-resolver.js。确定用户后,只需添加您自己的逻辑。
注册beforeRemote hook and check if current user is the $owner。
Joke.boforeRemote('findById', function(context, joke, next) {
// 1. find current user by id, using context.req.accessToken.userId
// 2. check if he is owner or not, by Role.isOwner
// 3. remove email from returned joke instance if user is not $owner
})
注意:涵盖所有 return 笑话的端点可能有点复杂。但是还有其他方法吗?
要修改 output/results,您可以使用 afterRemote 挂钩,根据 docs. The output/results are stored in ctx.result.
当调用类似于 GET http://myModel/id
时,'findById' 挂钩到您的 GET 请求中。如果您不在请求中包含 ID,请使用 'find',例如GET http://myModel
。请注意,在 'find' 的情况下,返回的实例(笑话)通常不只是一个,所以它在一个对象数组中。
Joke.afterRemote('findById', function(ctx, joke, next) {
//your code
});
- 获取当前登录用户的id:
var currentUser = context.req.accessToken.userId
- 将当前登录用户的用户标识与笑话所有者的用户标识进行比较。如果两者不相同(即
if (!(currentUser == joke.userId))
),则:
在调用 next() 之前,从返回的笑话实例中删除电子邮件属性。因为有时候有些方法行不通,这里有几个:
delete ctx.result.email;
ctx.result.email = '';
- 遍历属性并将它们转移到一个新的变量,除了电子邮件,然后保存那个新的变量结果:
ctx.result = newVar;
我只是想知道您将如何限制 属性 对 $owner 角色的访问权限。例如,在我的例子中,我有一个有作者的笑话。作者以用户为基础。我希望其他 "Authers" / 用户看到谁创造了这个笑话,但他们不应该看到作者的电子邮件,只有当作者是笑话本身的 $owner 时,才应该可以显示他们的电子邮件,只是为了这个案例。
查看内置用户模型,您可以看到他们使用 hidden 功能来隐藏密码,但是将其用于他们的电子邮件也会隐藏他们的电子邮件$owner,这不是我想要的
如果有什么不清楚的地方,请告诉我。
提前致谢
您可以创建自己的角色解析器。有关示例,请参见 https://github.com/strongloop/loopback-example-access-control/blob/master/server/boot/role-resolver.js。确定用户后,只需添加您自己的逻辑。
注册beforeRemote hook and check if current user is the $owner。
Joke.boforeRemote('findById', function(context, joke, next) {
// 1. find current user by id, using context.req.accessToken.userId
// 2. check if he is owner or not, by Role.isOwner
// 3. remove email from returned joke instance if user is not $owner
})
注意:涵盖所有 return 笑话的端点可能有点复杂。但是还有其他方法吗?
要修改 output/results,您可以使用 afterRemote 挂钩,根据 docs. The output/results are stored in ctx.result.
当调用类似于GET http://myModel/id
时,'findById' 挂钩到您的 GET 请求中。如果您不在请求中包含 ID,请使用 'find',例如GET http://myModel
。请注意,在 'find' 的情况下,返回的实例(笑话)通常不只是一个,所以它在一个对象数组中。
Joke.afterRemote('findById', function(ctx, joke, next) {
//your code
});
- 获取当前登录用户的id:
var currentUser = context.req.accessToken.userId
- 将当前登录用户的用户标识与笑话所有者的用户标识进行比较。如果两者不相同(即
if (!(currentUser == joke.userId))
),则: 在调用 next() 之前,从返回的笑话实例中删除电子邮件属性。因为有时候有些方法行不通,这里有几个:
delete ctx.result.email;
ctx.result.email = '';
- 遍历属性并将它们转移到一个新的变量,除了电子邮件,然后保存那个新的变量结果:
ctx.result = newVar;