Inside our LoopBack project, we run LBACL. This will prompt us for a model name. We choose products.
The generator asks for the scope. We choose all methods and properties. For access type, we select all. For the role, we select any unauthenticated user. For the permission, we explicitly deny access.
Now, if we look in our model definition, we see that we have a new object in the ACLs array which describes what we just created. Let's try this out in the API Explorer.
We start our server by running npm run dev, and open the API Explorer in the browser. Where we go to the GetProducts endpoints and we try it out, we see that we get an error message saying authorization required.
What we actually want to do is only allow the GetProducts endpoints, but disallow any other operations. That way, unauthenticated users cannot modify any data in their API, but can list it.
We hop over to our terminal and run LBACL a second time. We select product, single method, enter the name, find, select any unauthenticated user, and explicitly grant access.
In our product definition, we see that a new ACL rule got added to the ACLs array. When we start our server again and we try the same endpoint, we see that we can now list our products.
Other endpoints like delete/products still return authorization required. Because we want to have the same ACLs for the category model, we just copy the content of the ACLs array from product.json, and paste it in the ACLs array in category.json.
Instead of verifying through the API Explorer, let's add some tests to make sure our permissions are set as expected. We create the file ACL.test.js, and start by requiring app, expect, and request from common.
We currently don't export requests. Let's open our common.js, require SuperTest, create a constant called request which loads our app into SuperTest, and export request.
Because we did not install SuperTest yet, we go over to our terminal and install SuperTest as a dev dependency. Inside our ACL test, we create a new describe block for the ACL. Let's begin by testing the category model.
In the first test, we want to list the products and expect to have an HB200 response. In the next three tests for creating, updating, and deleting a category, we owe expect an HB401 authentication required response. When we run our tests, we see that they pass.
We add the same test for the product model. List is allowed. Create, update, and delete are denied. For the product model, we have an extra test for the buy methods.
Where we run our test, we see that we have one failing test. The buy method expected to be allowed, but was denied. We can fix that by opening product.json and change the string find into an array with find and buy. When we run our tests again, we see that they now all pass.