-1

I'm trying to deal with this problem while designing API backend I've been working on.

Example scenario: I have a REST server that has multiple objects of Product:

{
  Name: "SomethingSomething",
  SellPrice: 20,
  BuyPrice: 15
}

When a request to GET products is called, I'd like to show different data to different users. Guest users shouldn't be able to know BuyPrice, but admins should.

How is this properly solved? I've come with two ideas and I don't feel like any of them is perfect:


FIRST

Since my backend is JavaScript, I've been using a filter mask on requests. Guest users have defined mask that would remove BuyPrice from their response while admin users get all the data. This works good, but it's very loosely-typed(fields would be removed depending on context). Would cause headaches in strongly-typed languages that have nullable. Or even GraphQL implementation would need every field to be nullable and wouldn't allow(for example) to have required params(since basically anything can be removed). Admin context pow:

{
  Name: "SomethingSomething",
  SellPrice: 20,
  BuyPrice: 15
}

Guest context pow:

{
  Name: "SomethingSomething",
  SellPrice: 20
}

SECOND

Create different sub-objects for different cases. Something like "ProductPublicInfo" to be accessible by both guest and admin users and "ProductPriceInfo" to be accessible only by admin users. This, though, doesn't allow me such a granular control over things like the first option. Admin context pow:

{
  Id: 69
  Name: "SomethingSomething",
  SellPrice: 20,
}
{
  Product: 69,
  BuyPrice: 15
}

Guest context pow:

{
  Id: 69
  Name: "SomethingSomething",
  SellPrice: 20
}

I'd greatly appreciate any advices from you guys. Thank you!

Gork
  • 1
  • 1

1 Answers1

0

I would make different endpoints for a guest and an Admin. But if that's too much hassle, an approach could be returning all the fields, always, regardless of the user who's making the query. However, the information in the fields could be masked as follows:

For an Admin

Name: { "Vacuum Cleaner" }
ProductPriceInfo { "1.5 USD" } 

For a Guest

Name: { "Vacuum Cleaner" }
ProductPriceInfo { "Info not available for this user" }
Felipe La Rotta
  • 343
  • 3
  • 13