How to handle request based on user role [PLUGIN]

Hi,
In the hello-exchange plugin example, How can I handle response based on user role in endpoints? For example:

init()
  .then(() => {
    app.get(
      "/plugins/hello-exchange/hi",
      [
        toolsLib.security.verifyBearerTokenExpressMiddleware(["admin"]),
        query("user_id").isInt({ min: 1 }).toInt().optional()
      ],
      async (req, res) => {
      }
....

As a response, I want to send the string ‘Hi admin’ if the request is coming from admin and ‘Hi dear’ if the request comes from the other users(aren’t admin).

This middleware you got already takes care of the access control for admin.

        toolsLib.security.verifyBearerTokenExpressMiddleware(["admin"]),

You can add your logic in the body of async (res, res) and the code only reaches to the body if the request is coming from admin.

But if the request isn’t coming from admin, it returned the status 403 and I can’t handle it with difference response.
How can I handle the response based on user role?

1 Like

With this middleware you ensure that no user other than admin can reach this endpoint.

toolsLib.security.verifyBearerTokenExpressMiddleware(["admin"])

If you want to know which role is sending the request, you better decode the JWT token yourself. There is authorization header that includes the bearer token.

You need to use jwt.verify function using jsonwebtoken library. If you read about the verifyBearerTokenExpressMiddleware functions code you can get an idea how it is done.

Once you verify it the scope of the token tell you which role is sending the request.

The code below should give you some ideas:

jwt.verify(tokenString, SECRET, (verificationError, decodedToken) => {
     if (!verificationError && decodedToken) {
           console.log(decodedToken.scopes)
     }
});
2 Likes