All files / backend/koa-middleware hasPermissions.js

100% Statements 10/10
100% Branches 3/3
100% Functions 3/3
100% Lines 9/9
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 531x                                                                     15x 16x 14x 6x         6x 6x     8x       1x  
const HttpError = require('./HttpError');
 
/**
 * @swagger
 * definition:
 *   PermissionError:
 *     description:
 *       HTTP status code 403.
 *       User has no permission to access the requested resource.
 *       Example cause might be when user wants to receive group data but he is not part of the group.
 *
 *     properties:
 *       errorId:
 *         type: string
 *         format: uuid
 *
 *       errorCode:
 *         type: string
 *         example: NO_PERMISSION
 *
 *       errorMessage:
 *         type: string
 *         example: You must have permission "canReadJoinedGroups" in order to access this API
 */
 
/**
 * This koa middleware determines if all sent `permissions` are met
 * in the already loaded `ctx.state.userPermissions`
 *
 * @category middleware
 *
 * @param {string[]} permissions List of permissions that needs be in `ctx.state.userPermissions`
 * @return {Function} koa wrapper middleware
 */
function hasPermissions(permissions = []) {
  return async (ctx, next) => {
    const unmetPermission = permissions.find((permission) => !ctx.state.userPermissions.includes(permission));
    if (unmetPermission) {
      const error = new HttpError(
          403,
          'NO_PERMISSION',
          `You must have permission "${unmetPermission}" in order to access this API`
      );
      ctx.app.emit('error', error, ctx);
      return;
    }
 
    return next();
  };
}
 
module.exports = hasPermissions;