How to protect properties for different roles using loopback

I'm just wondering how to restrict access to the properties of only the $ owner role. For example, in my case, I have a Joke that has an Author. The author has a User as a basis. I would like other Authers / Users to see who created the Joke, but they should not see Authers email only if the author owns the joke itself, it should be OK to show my email, just for the sake of this case.

Looking at the built-in User model, you can see that they use a hidden function to hide the password, but using this for their email will also hide their email for the owner $, which I did not want

Let me know if something is unclear.

Thanks in advance

+4
source share
3 answers

Register beforeRemote hook and check if the current user is $ 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
})

Note. It can be a little difficult to cover all the endpoints that return jokes. But is there any other way to do this?

+1
source

To change the output of /, you can use afterRemote , according to the docs . Results / results are saved in ctx.result .

'findById' GET, GET http://myModel/id. "find", , . GET http://myModel. , "find" () , .

Joke.afterRemote('findById', function(ctx, joke, next) {
  //your code
});
  • : var currentUser = context.req.accessToken.userId
  • . (.. if (!(currentUser == joke.userId))), :
  • next() email joke. , :

    • delete ctx.result.email;
    • ctx.result.email = '';
    • var, , var: ctx.result = newVar;
0

You can create your own role resolver. See https://github.com/strongloop/loopback-example-access-control/blob/master/server/boot/role-resolver.js for an example. Just add your own logic as soon as you define the user.

-1
source

All Articles