Search code examples
loopbackjsacl

Loopback: Hide some properties for some user roles


There is a model like this

{
  name,
  budget
}

And there is a role reviewer

Is there any way to hide the budget field for the reviewers?


Solution

  • You can use a remote hook for that model. For example your code could look like this:

    MyModel.afterRemote('**', function(ctx, modelInstance, next) {
      if (ctx.result) {
        if (checkIfUserHasRole('reviewer')) { // <-- you need to implement this function
          // if you are going to return a list of items, eg. from Model.find(...) 
          if (Array.isArray(modelInstance)) { 
            ctx.result = ctx.result.map(item => {
              return modifyYourProperties(item); // <-- you need to implement this function
            }
          }
          // if you are going to return a single item, eg. from Model.findById(...)
          else {
            ctx.result = modifyYourProperties(ctx.result); // <-- as above...
            }
    
          });
        }
      }
      next();
    }
    

    So now, on every remote call to your model, you can modify the results. They are already processed but not yet returned to the requester, so here is where you can hide desired properties.

    Of course, you need to implement methods checkIfUserHasRole and modifyYourProperties to do what you are going to achieve. You can read more about remote hooks here: https://loopback.io/doc/en/lb3/Remote-hooks.html