All files / lib/lambda/middleware hasPermissions.ts

100% Statements 8/8
100% Branches 9/9
100% Functions 2/2
100% Lines 7/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                    6x     7x 7x   7x 2x         5x       2x        
import { MiddlewareObj, Request } from "@middy/core";
import { createError } from "@middy/util";
import { isCmsUser } from "shared-utils";
 
import { getAuthUserFromRequest, getPackageFromRequest } from "./utils";
 
/**
 * Checks the user's permissions to determine if they can access the package.
 * @returns {MiddlewareObj} middleware the validate permission for a user to view a package before the handler runs
 */
export const canViewPackage = (): MiddlewareObj => ({
  before: async (request: Request) => {
    // Get the user to check if they are authorized to see the package
    const user = await getAuthUserFromRequest(request);
    const packageResult = await getPackageFromRequest(request);
 
    if (!user || !packageResult) {
      throw createError(500, JSON.stringify({ message: "Internal server error" }), {
        expose: true,
      });
    }
 
    if (
      !isCmsUser(user) &&
      (!user.states || !user.states.includes(packageResult?._source?.state.toUpperCase()))
    ) {
      throw createError(403, JSON.stringify({ message: "Not authorized to view this resource" }));
    }
  },
});