export function isRouteRequiringUserRolesCheck()

in src/msha/routes-engine/rules/routes.ts [34:99]


export function isRouteRequiringUserRolesCheck(
  req: http.IncomingMessage,
  matchingRoute: SWAConfigFileRoute | undefined,
  isFunctionRequest: boolean,
  authStatus: number
) {
  logger.silly(`checking authorizations for route`);

  if (!matchingRoute) {
    logger.silly(` - no matching rule`);
    logger.silly(` - access authorized`);
    return true;
  }

  if (matchingRoute.allowedRoles?.length === 0) {
    logger.silly(` - no allowedRoles provided`);
    logger.silly(` - access authorized`);
    return true;
  }

  const shouldCheckRoles = Boolean(
    authStatus != AUTH_STATUS.HostNameAuthLogin &&
      matchingRoute.allowedRoles &&
      matchingRoute.allowedRoles.length > 0 &&
      !matchingRoute.allowedRoles.includes("anonymous")
  );

  logger.silly(` - shouldCheckRoles: ${chalk.yellow(shouldCheckRoles)}`);

  const shouldLookupAuthCookie =
    shouldCheckRoles || isFunctionRequest || authStatus == AUTH_STATUS.AuthMe || authStatus == AUTH_STATUS.HostNameAuthPurge;

  logger.silly(` - shouldLookupAuthCookie: ${chalk.yellow(shouldLookupAuthCookie)}`);

  if (shouldLookupAuthCookie) {
    const clientPrincipalInternal = req.headers?.cookie ? decodeCookie(req.headers?.cookie) : null;
    const doesAuthCookieExist = !!clientPrincipalInternal;

    if (shouldCheckRoles && !doesAuthCookieExist) {
      logger.silly(` - secure route found but cookies not found`);
      logger.silly(` - access not authorized`);
      return false;
    }

    const userRoles = clientPrincipalInternal?.userRoles;
    logger.silly(` - userRoles: ${chalk.yellow(userRoles?.length ? userRoles : "<empty>")}`);
    logger.silly(` - allowedRoles: ${chalk.yellow(matchingRoute.allowedRoles)}`);
    logger.silly(matchingRoute);

    const matchedRoles = userRoles?.filter((value) => matchingRoute.allowedRoles?.includes(value));
    logger.silly(` - matchedRoles: ${chalk.yellow(matchedRoles?.length ? matchedRoles : "<empty>")}`);

    const isUserAuthenticatedOrAnonymous = matchedRoles?.length! > 0;
    logger.silly(` - isUserAuthenticatedOrAnonymous: ${chalk.yellow(isUserAuthenticatedOrAnonymous)}`);

    if (shouldCheckRoles && !isUserAuthenticatedOrAnonymous) {
      logger.silly(` - secure route found but roles don't match`);
      logger.silly({ allowedRoles: matchingRoute.allowedRoles });
      logger.silly(` - access not authorized`);
      return false;
    }
  }

  logger.silly(` - access authorized`);
  return true;
}