1
votes

So I have this function in Koa, that basically checks if a user can access a specific route.

exports.requireRole = async role =>
  async (ctx, next) => {
    const { user } = ctx.state.user;
    try {
      const foundUser = await User.findById(user.id);
      // If the user couldn't be found, return an error
      if (!foundUser) {
        ctx.status = 404;
        ctx.body = { errors: [{ error: ERRORS.USER_NOT_FOUND }] };
      } else {
        // Otherwise, continue checking role
        if (getRole(user.role) >= getRole(role)) {
          await next();
        }

        ctx.status = 403;
        ctx.body = { errors: [{ error: ERRORS.NO_PERMISSION }] };
      }
    } catch (err) {
      ctx.throw(500, err);
    }
  };

And I want to use it as a middleware:

router.delete('/:id', combine([jwtAuth, requireRole(ROLES.ADMIN)]), deleteUser);

But then I get an error saying:

middleware must be a function not object

This happens only when I try to pass an argument into it.

What am I doing wrong here?

2

2 Answers

1
votes

The issue you are having is due to the fact that Promises are objects, and async functions return Promises. You need to change your initial function to be as follows:

exports.requireRole = role =>

instead of

exports.requireRole = async role =>

I was going over middleware myself, and ran into this issue as well.

0
votes

Your middleware looks fine, what is combine?

Also, since you are using koa-router you don't need it.

router.delete('/:id', jwtAuth, requireRole(ROLES.ADMIN), deleteUser);