Role based authorization best practice

Hi,

I would like to get help in role based authorization. Let assume the following scenario:

User type:

  • user
  • admin

Routes:

  • api/books
  • api/authors

The ‘user’ can read the books and read and add authors. The ‘admin’ can add, read, update and delete books and authors.

In this case do I need to write a standalone middleware function for every single route to check the permission or is it possible to solve it with one middleware? I give a short example:

GET /api/books → admin, user
POST /api/books → admin
PUT /api/books → admin
DELETE /api/books → admin

GET /api/authors → admin, user
POST /api/authors → admin, user
PUT /api/authors → admin
DELETE /api/authors → admin

So, in the case of GET /api/books, GET /api/authors and POST /api/authors I need to check if the user is ‘user’ or ‘admin’ (if yes it is authorized otherwise not). But in the rest of the routes I need to check only it is admin or not. So do I need two middleware to solve it? Is it a good practice?

Thank you!